Skip to content

Instantly share code, notes, and snippets.

@eric-norcross
Last active December 27, 2015 15:19
Show Gist options
  • Save eric-norcross/7346423 to your computer and use it in GitHub Desktop.
Save eric-norcross/7346423 to your computer and use it in GitHub Desktop.
Fabrication has_many though. I can't figure out how to set this up properly. I've tried a few methods but can never get the test to pass.
class Brand < ActiveRecord::Base
attr_accessible :title,
:style_ids
has_many :brand_styles, dependent: :destroy
has_many :styles, through: :brand_styles
validates_presence_of :title
validates_presence_of :styles
end
Fabricator(:brand) do
title "Coca Cola"
# This returns the error:
#1) Brand has a valid factory
# Failure/Error: Fabricate(:brand).should be_valid
# ActiveRecord::RecordInvalid:
# Validation failed: Styles can't be blank
# ./spec/models/brand_spec.rb:5:in `block (2 levels) in <top (required)>'
# before_save do |brand|
# Fabricate(:brand_style, :brand => brand, :style => Fabricate(:style))
# end
#This returns the error:
#1) Brand has a valid fabrication
# Failure/Error: Fabricate(:brand).should be_valid
# ActiveRecord::UnknownAttributeError:
# unknown attribute: styles
# ./spec/fabricators/brand_fabricator.rb:9:in `block (2 levels) in <top (required)>'
# ./spec/models/brand_spec.rb:5:in `block (2 levels) in <top (required)>'
before_save do |brand|
Fabricate(:brand_style, :brand => brand, :styles => [Fabricate(:style)])
end
end
require 'spec_helper'
describe Brand do
it "has a valid fabrication" do
Fabricate(:brand).should be_valid
end
end
class BrandStyle < ActiveRecord::Base
attr_accessible :brand_id,
:style_id
belongs_to :brand
belongs_to :style
end
Fabricator(:brand_style) do
brand
style
end
class Style < ActiveRecord::Base
attr_accessible :title
has_many :brand_styles, dependent: :destroy
has_many :brands, through: :brand_styles
validates_presence_of :title
end
Fabricator(:style) do
title "Beverage"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment