这可能很简单,但是我在任何地方都找不到示例。
我有两个工厂:
FactoryGirl.define do
factory :profile do
user
title "director"
bio "I am very good at things"
linked_in "http://my.linkedin.profile.com"
website "www.mysite.com"
city "London"
end
end
FactoryGirl.define do
factory :user do |u|
u.first_name {Faker::Name.first_name}
u.last_name {Faker::Name.last_name}
company 'National Stock Exchange'
u.email {Faker::Internet.email}
end
end
我想做的是在创建个人资料时覆盖一些用户属性:
p = FactoryGirl.create(:profile, user: {email: "test@test.com"})
或类似的东西,但是我无法正确使用语法。错误:
ActiveRecord::AssociationTypeMismatch: User(#70239688060520) expected, got Hash(#70239631338900)
我知道我可以通过首先创建用户,然后将其与配置文件相关联来做到这一点,但我认为必须有更好的方法。
或这将工作:
p = FactoryGirl.create(:profile, user: FactoryGirl.create(:user, email: "test@test.com"))
但这似乎太复杂了。有没有更简单的方法来覆盖关联的属性?
正确的语法是什么?
最佳答案
根据FactoryGirl的一位创建者,您不能将动态参数传递给关联帮助器(Pass parameter in setting attribute on association in FactoryGirl)。
但是,您应该可以执行以下操作:
FactoryGirl.define do
factory :profile do
transient do
user_args nil
end
user { build(:user, user_args) }
after(:create) do |profile|
profile.user.save!
end
end
end
然后,您可以按照自己的意愿调用它:
p = FactoryGirl.create(:profile, user_args: {email: "test@test.com"})
关于ruby - 关联对象的FactoryGirl覆盖属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16297357/