【问题标题】:How use the attributes of a fabricator within the definition of the fabricator?如何在制造商的定义中使用制造商的属性?
【发布时间】:2014-10-06 10:24:16
【问题描述】:

我有一个UserUserProfile 模型。目前这两个模型都有first_namelast_nameemail属性,它们必须相同。稍后我将从User 中删除这些属性,但目前我希望这样。一个UserProfilebelongs_to 一个User。我已经像这样定义了UserProfile 制造商:

Fabricator(:user_profile) do
  first_name { Faker::Name.first_name }
  last_name  { Faker::Name.last_name }
  email      { Faker::Internet.email }
  user       { Fabricate :user }
end

User 制造商:

Fabricator(:user) do
  email         { Faker::Internet.email }
  first_name    { Faker::Name.first_name }
  last_name     { Faker::Name.last_name }
  last_login_at { Time.now }
  organization  { Fabricate :organization }
end

问题是现在,当我制作用户配置文件时,属性不一样了:

user_profile.first_name == user_profile.user.first_name # => false

在用户配置文件制造者的定义中,我尝试了这个,但没有奏效:

user       { Fabricate :user, first_name: first_name, last_name: last_name, email: email }

如何在不使用硬编码值替换 Faker 的情况下制作具有相同属性的用户和用户配置文件?

【问题讨论】:

    标签: fixtures model-associations modelattribute fabrication-gem


    【解决方案1】:

    我认为最简单的方法是稍微重新组织您的用户配置文件并使用来自用户的数据来填充其字段。

    Fabricator(:user_profile) do
      user
      first_name { |attrs| attrs[:user].first_name }
      last_name  { |attrs| attrs[:user].last_name }
      email      { |attrs| attrs[:user].email }
    end
    
    Fabricator(:user) do
      email         { Faker::Internet.email }
      first_name    { Faker::Name.first_name }
      last_name     { Faker::Name.last_name }
      last_login_at { Time.now }
      organization
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-08
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多