FactoryGirl覆盖关联对象的属性 [英] FactoryGirl override attribute of associated object

查看:112
本文介绍了FactoryGirl覆盖关联对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是愚蠢的简单,但我找不到任何地方的例子。

This is probably silly simple but I can't find an example anywhere.

我有两个工厂:

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

我想要做的是覆盖某些用户属性,当我创建一个配置文件:

What I want to do is override some of the user attributes when I create a profile:

p = FactoryGirl.create(:profile, user: {email: "test@test.com"})

或类似的东西,但我不能得到正确的语法。错误:

or something similar, but I can't get the syntax right. Error:

ActiveRecord::AssociationTypeMismatch: User(#70239688060520) expected, got Hash(#70239631338900)

我知道我可以先创建用户,然后将其与关联轮廓做到这一点,但我认为必须有一个更好的办法。

I know I can do this by creating the user first and then associating it with the profile, but I thought there must be a better way.

或者这将工作:

p = FactoryGirl.create(:profile, user: FactoryGirl.create(:user, email: "test@test.com"))

不过,这似乎过于复杂。有没有更简单的覆盖关联的属性的方法吗?
什么是正确的语法为这个?

but this seems overly complex. Is there not a simpler way to override an associated attribute? What is the correct syntax for this??

推荐答案

据FactoryGirl的创建者之一,你不能传递动态参数的关联助手(<一个href=\"http://stackoverflow.com/questions/10434572/pass-parameter-in-setting-attribute-on-association-in-factorygirl\">Pass参数在FactoryGirl 上设置的关联属性)。

According to one of FactoryGirl's creators, you can't pass dynamic arguments to the association helper (Pass parameter in setting attribute on association in FactoryGirl).

然而,你应该能够做这样的事:

However, you should be able to do something like this:

FactoryGirl.define do
  factory :profile do
    ignore do
      user_args nil
    end
    user { build(:user, user_args) }

    after(:create) do |profile|
      profile.user.save!
    end
  end
end

然后就可以调用它就像你想:

Then you can call it almost like you wanted:

p = FactoryGirl.create(:profile, user_args: {email: "test@test.com"})

这篇关于FactoryGirl覆盖关联对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆