这可能很简单,但我在任何地方都找不到例子。
我有两个工厂:
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: "[email protected] /cdn-cgi/l/email-protection"})
或类似的东西,但我无法得到正确的语法。错误:
ActiveRecord::AssociationTypeMismatch: User(#70239688060520) expected, got Hash(#70239631338900)
我知道我可以通过先创建用户然后将其与配置文件关联来做到这一点,但我认为必须有更好的方法。
或者这会起作用:
p = FactoryGirl.create(:profile, user: FactoryGirl.create(:user, email: "[email protected] /cdn-cgi/l/email-protection"))
但这似乎过于复杂。是否没有更简单的方法来覆盖关联的属性?
正确的语法是什么?
根据 FactoryGirl 的创建者之一的说法,您无法将动态参数传递给关联助手(在 FactoryGirl 关联的设置属性中传递参数 https://stackoverflow.com/questions/10434572/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: "[email protected] /cdn-cgi/l/email-protection"})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)