我一直在努力幾個小時,讓工廠女孩創建兩個工廠 - 一個用於用戶,一個用於組織。使用工廠女孩創建HABTM協會
但我似乎並沒有理解我如何在工廠中反映'has_and_belongs_to_many'關係,只要我嘗試創建組織並將其與管理員用戶關聯,我會遇到各種錯誤消息(具體取決於我使用的方法)。 我的模型似乎工作正常,我的種子文件填充開發數據庫,並創建所有的關聯。
現在我的文件是這樣的:
用戶工廠
FactoryGirl.define do
factory :user do
email '[email protected]'
password 'password'
password_confirmation 'password'
after(:create) {|user| user.add_role(:user)}
factory :owner do
after(:create) {|user| user.add_role(:owner)}
end
factory :admin do
after(:create) {|user| user.add_role(:admin)}
end
factory :superadmin do
after(:create) {|user| user.add_role(:superadmin)}
end
end
end
組織工廠
FactoryGirl.define do
factory :organization do |f|
f.name "example"
f.website "www.aquarterit.com"
f.association :users, :factory => :admin
end
end
在我的規格
我測試:
describe Organization do
it "has a valid factory" do
FactoryGirl.create(:organization).should be_valid
end
it "is invalid without a name" do
FactoryGirl.build(:organization, name: nil).should_not be_valid
end
it "is associated with at least one admin user" do
FactoryGirl.create(:organization)
it { should have_and_belong_to_many(:users)}
end
end
所有三個測試是失敗的,這裏的錯誤消息:
1) Organization has a valid factory
Failure/Error: FactoryGirl.create(:organization).should be_valid
NoMethodError:
undefined method `each' for #<User:0x007fadbefda688>
# ./spec/models/organization_spec.rb:7:in `block (2 levels) in <top (required)>'
2) Organization is invalid without a name
Failure/Error: FactoryGirl.build(:organization, name: nil).should_not be_valid
NoMethodError:
undefined method `each' for #<User:0x007fadc29406c0>
# ./spec/models/organization_spec.rb:11:in `block (2 levels) in <top (required)>'
3) Organization is associated with at least one admin user
Failure/Error: organization = FactoryGirl.create(:organization)
NoMethodError:
undefined method `each' for #<User:0x007fadc2a3bf20>
# ./spec/models/organization_spec.rb:15:in `block (2 levels) in <top (required)>'
任何幫助是一如既往非常感謝!
更新
在理論,分配角色的用戶應分配一個管理員對組織工作的工作原理是一樣的。但是,如果我改變organizations.rb到
FactoryGirl.define do
factory :organization do
name "example"
website "www.aquarterit.com"
after(:create) {|organization| organization.add_user(:admin)}
end
end
我得到以下錯誤(我有寶石早該安裝):
1) Organization is associated with at least one admin user
Failure/Error: it { should have_and_belong_to_many(:users)}
NoMethodError:
undefined method `it' for #<RSpec::Core::ExampleGroup::Nested_1:0x007ff2395f9000>
# ./spec/models/organization_spec.rb:16:in `block (2 levels) in <top (required)>'
I th墨水本文解答您的問題:http://stackoverflow.com/questions/1484374/how-to-create-has-and-belongs-to-many-associations-in-factory-girl –
謝謝 - 我發現之前,但據我瞭解,它不使用最新的語法; factorygirl現在推薦使用'after(:create)'來添加關聯,不是嗎?更新了原來的問題,包括一個修正的組織工廠 –