我有一个包含一个配置文件的用户模型。当我像这样创建用户时,会自动创建配置文件;
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 中创建用户后,我是否应该在测试中手动分配配置文件属性?
最佳答案
您可以像这样跳过 after_create 回调:
FactoryGirl.define do
factory :user do
after(:build) { |user| user.class.skip_callback(:create, :after, :create_setting) }
end
end
关于ruby-on-rails - 当我已经在模型中创建关联时,如何测试具有与 FactoryGirl 的 has_one 关联的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11220048/