我一直在努力几个小时,让工厂女孩创建两个工厂 - 一个用于用户,一个用于组织。使用工厂女孩创建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)'来添加关联,不是吗?更新了原来的问题,包括一个修正的组织工厂 –