【问题标题】:How to test a model with a has_one association with FactoryGirl when I am already creating the association in the model当我已经在模型中创建关联时,如何测试具有与 FactoryGirl 的 has_one 关联的模型
【发布时间】:2012-06-27 05:40:11
【问题描述】:

我有一个拥有个人资料的用户模型。当我这样创建用户时,配置文件会自动创建;

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  after_create :create_profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

这一切都很好,每个用户都会创建一个默认配置文件。

不过,我想对我的用户模型进行一些测试,而这正是我苦苦挣扎的地方。

我正在使用 FactoryGirl 并想创建一个这样的用户

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "user_#{n}@example.com"}
    sequence(:username) {|n| "user_#{n}"}
    password "secret"
    factory :activated_user do
      before(:create) {|user| user.activated = true}
      association :profile, factory: :profile_for_activated_user
    end
  end
end

FactoryGirl.define do
  factory :profile do
    factory :profile_for_activated_user do
      first_name "Johnny"
      last_name "User"
    end
  end
end

这就是我出错的地方。 after_create 回调(我想要的)覆盖了 FactoryGirl 创建的关联(在FactoryGirl.create :activated_user 上),所以我最终得到一个空白配置文件和失败的测试。我是否需要更改在模型中创建关联的方式(我不应该这样做 - 我不应该修改我的代码以适应我的测试工具)或者有没有办法在 FactoryGirl 中管理这个?在 FactoryGirl 中创建用户后,我是否应该在测试中手动分配配置文件属性?

【问题讨论】:

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


    【解决方案1】:

    你可以像这样跳过 after_create 回调:

    FactoryGirl.define do
      factory :user do
        after(:build) { |user| user.class.skip_callback(:create, :after, :create_setting) }
      end
    end
    

    【讨论】:

    • 这很好,尽管 after_build 给出了弃用通知。我使用 after(:build) 并且效果很好。谢谢。
    猜你喜欢
    • 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
    相关资源
    最近更新 更多