【问题标题】:How do I override an association (by using a Factory) when using FactoryGirls?使用 FactoryGirls 时如何覆盖关联(通过使用工厂)?
【发布时间】:2013-07-16 20:27:25
【问题描述】:

在我的应用程序中,我有一个 User 模型 has_one Profile 模型。然后我有一个Service 模型belongs_to 一个User

我正在尝试使用 FactoryGirl 创建一个不同于默认值的 Profile,然后将 User(通过 FactoryGirl 创建)关联到 Profile,最后将 User 关联到 @ 987654331@.

@profile_first_name = FactoryGirl.create(:profile, first_name: "UniqueFirstName")

@user = FactoryGirl.create(:user, profile: @profile_first_name)

使用调试器检查,此时似乎一切正常。用户有正确的名字:

[#<Profile id: 1, user_id: 1, first_name: "UniqueFirstName", ...

然后我运行代码来创建一个服务并将这个自定义用户 @user 关联到该服务:

@service = FactoryGirl.create(:service, name: "Tester Service", user: @user)

再次,使用调试器检查并查询数据库,此服务应该与 first_name = 'UniqueFirstName' 的用户相关联。相反,它具有默认配置文件(可能是因为它使用的是默认用户工厂):

#<Profile id: 2, user_id: 1, first_name: "John" ...

我需要知道如何通过覆盖属性来创建工厂,然后在其他工厂中使用这些工厂(通常用于任何类型的关系)。我在这里错过了什么?

仅供参考,这是我的工厂:

#factories/profile.rb
FactoryGirl.define do
  factory :profile do
    first_name  "John"
    last_name   "Doe"
    shop_name   "Casual"
    name_layout "name"
    country     "US"
    city        "Boston"
    about <<-EOF
      Lorem ipsum dolor sit amet, consectetur adipisicing elit,
      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
      ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
      in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
      sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
      mollit anim id est laborum.
    EOF
  end
end


#factories/user.rb
FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "user+#{n}@example.com" }
    password 'testtest'
    password_confirmation 'testtest'

    after(:build) do |user|
      user.profile = FactoryGirl.build(:profile, user: user)
    end
  end
...
end

我尝试过的事情: 手动设置服务用户的个人资料:

@service = FactoryGirl.create(:service, name: "Globe Tester", user: @maker1)
@service.user.profile = @profile_first_name

那也没用。

【问题讨论】:

  • 能否把服务工厂的代码也发一下?

标签: ruby-on-rails testing factory-bot


【解决方案1】:

为什么在第二个示例中您的个人资料 id=2?看起来您正在创建两个配置文件。

老实说,我通常通过 id 而不是关联模型来设置它,并且没有遇到过这个问题(比如 profile_id 而不是 profile)。你也可能想检查脏?对象的价值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多