私はRoR3.2.3でFactoryGirl3.3.0を使用しています
私はそのようなhas_oneプロファイルを持つユーザーモデルを持っています。
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_profile
とがコールバック:activated_user_without_profile
を継承するのに対し、とファクトリは継承しないということでしたが、そのようには機能していません。これが私の問題を示すためのコンソールからの抜粋です。after(:build)
:user_without_profile
:new_user_with_profile
: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を作成すると、プロファイルは期待どおりに作成されますが、2回目(:new_user_without_profileを作成した後)は、それ以上作成されません。after(:build)コールバックが再度呼び出されていないようです(何かを出力するためにコードを追加すると、ターミナルに表示されません)。ここで何が悪いのかわかりません。他に誰かいますか?