1

我正在使用带有 RoR 3.2.3 的 FactoryGirl 3.3.0

我有一个用户模型,它有这样的个人资料;

class User < ActiveRecord::Base
  has_secure_password
  has_one :profile, dependent: :destroy
  accepts_nested_attributes_for :profile, update_only: true
  attr_accessible :email, :username, :password, :password_confirmation, :profile_attributes
  before_create :build_profile
end

class Profile < ActiveRecord::Base
  attr_accessible :first_name, :last_name
  belongs_to :user
  validates :user, presence: true
  validates :first_name, presence: true, on: :update
  validates :last_name, presence: true, on: :update
end

在我的 rspec 测试中,我有时需要阻止 before_create :build_profile 运行,这样我就可以拥有一个没有配置文件的用户。我用 FactoryGirl 回调来管理这个

after(:build) {|user| user.class.skip_callback(:create, :before, :build_profile)}

我的用户工厂定义如下;

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "user_#{n}@example.com"}
    sequence(:username) {|n| "user_#{n}"}
    password "secret"
    factory :user_with_profile do
      factory :new_user_with_profile do
        before(:create) {|user| user.activated = false}
      end
      factory :activated_user_with_profile do
        before(:create) {|user| user.activated = true}
      end
    end
    factory :user_without_profile do
      after(:build) {|user| user.class.skip_callback(:create, :before, :build_profile)}
      factory :new_user_without_profile do
        before(:create) {|user| user.activated = false}
      end
      factory :activated_user_without_profile do
        before(:create) {|user| user.activated = true}
      end
    end
  end
end

我的期望是:new_user_without_profileand:activated_user_without_profile会继承after(:build)回调,:user_without_profile:new_user_with_profileand:activated_user_with_profile工厂不会,但它并不是那样工作的。这是控制台的摘录,以演示我的问题;

irb(main):001:0> user = FactoryGirl.create :new_user_with_profile
irb(main):002:0> user.profile
=> #<Profile id: 11, first_name: "", last_name: "", created_at: "2012-07-10 08:40:10", updated_at: "2012-07-10 08:40:10", user_id: 18>
irb(main):003:0> user = FactoryGirl.create :new_user_without_profile
irb(main):004:0> user.profile
=> nil
irb(main):005:0> user = FactoryGirl.create :new_user_with_profile
irb(main):006:0> user.profile
=> nil

所以,我第一次创建 :new_user_with_profile 时,会按预期创建配置文件,但第二次(在创建 :new_user_without_profile 之后),它就没有了!after(:build) 回调似乎没有被再次调用(如果我添加一些代码来输出一些东西,我在终端中看不到它)。我不知道这里出了什么问题。还有其他人吗?

4

1 回答 1

2

This is a dirty solution but have you tried to write the definition of the callback in the factory :user_with_profile:

after(:build) {|user| user.class.set_callback(:create, :before, :build_profile)}

Does it work?

于 2012-07-10T11:11:30.463 回答