我是FactoryGirl的新手(一般測試),我試圖建立一個has_many關係的工廠。到目前爲止,我發現的所有例子都使用了舊版本的工廠女孩,官方文檔並沒有那麼有用。Rspec 2.14,FactoryGirl 4.2,Rails 3.2.11 - has_many通過
當我運行我的測試,它說:
Failures:
1) Brand has a valid factory
Failure/Error: FactoryGirl.create(: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)>'
brand.rb
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
style.rb
class Style < ActiveRecord::Base
attr_accessible :title
has_many :brand_styles, dependent: :destroy
has_many :brands, through: :brand_styles
validates_presence_of :title
end
brand_style.rb個
class BrandStyle < ActiveRecord::Base
attr_accessible :brand_id,
:style_id
belongs_to :brand
belongs_to :style
end
工廠
FactoryGirl.define do
factory :brand do
title "Some Brand"
after(:create) do |brand|
brand.style create(:brand_style, brand:brand, style: FactoryGirl.build(:style))
brand.reload
end
end
factory :style do
title "Some Style"
end
factory :brand_style do
brand
style
end
end
規範
require 'spec_helper'
describe Brand do
it "has a valid factory" do
FactoryGirl.create(:brand).should be_valid
end
end
---編輯---
我修改我的事實每達明羅切斯建議ORY,我現在收到此錯誤:
Failures:
1) Brand has a valid factory
Failure/Error: FactoryGirl.create(:brand).should be_valid
NoMethodError:
undefined method `primary_key' for #<FactoryGirl::Declaration::Implicit:0x007fc581b2d178>
# ./spec/factories/brand.rb:4:in `block (3 levels) in <top (required)>'
# ./spec/models/brand_spec.rb:5:in `block (2 levels) in <top (required)>'
改性工廠
FactoryGirl.define do
factory :brand do |brand|
brand.title "Some Brand"
brand.styles { build_list(:brand_style, 1, brand: brand, style: build(:style)) }
end
factory :style do
title "Some Style"
end
factory :brand_style do
brand
style
end
end
我已經更新了我的代碼(以上)根據您的建議,現在我得到一個新的錯誤'未定義的方法'primary_key'爲#'。有任何想法嗎? –
你能更新你的':品牌'塊嗎?它應該按照':style'和':brand_style'。不要傳入'|品牌|'。使用與其他工廠相同的格式。不能確定這是問題,但請首先糾正。如果錯誤仍然存在,則可能是您的rails版本和factory_girl版本之間不兼容。 –
本來我剛剛更新'create(:after)'block,但是,當我運行測試時,它在'brand:brand'部分的'undefined method'品牌'上失敗,導致我添加'|品牌|'。我會嘗試更新其他工廠的格式以使用'| whatever |'來消除這種可能性。另外,爲了參考我正在使用rails 3.2.11 –