提问人:Dave 提问时间:6/20/2022 更新时间:6/21/2022 访问量:116
在 Rails 4 和 FactoryGirl 中,如何覆盖基础工厂的 “after(:build)” 方法?
In Rails 4 and FactoryGirl, how do I override the base factory's "after(:build)" method?
问:
我正在将 Rails 4.2.3 与 FactoryGirl 一起使用。我为我的用户准备了这个工厂
FactoryGirl.define do
…
factory :user do
after(:build) do |user, vars|
print "in main user after build.\n"
def user.publish
# and here you can stub method response if you need
end
end
…
trait :with_callbacks do
after(:build) do |user, vars|
print "after build my user\n"
end
…
end
我想覆盖我的基本“after(:build)”方法,所以我创建了特征“with_callbacks”。但是当我用我的特质打电话给我的工厂时
create(:user, :my_user)
似乎两个“after(:build)”方法都是根据输出调用的......
after build my user
in main user after build.
有没有办法操纵东西,以便我可以覆盖基础工厂的“after(:build)”方法?
答:
0赞
melcher
6/21/2022
#1
不确定您要做什么,但另一种选择是使用瞬态变量(在 FactoryBot 5.0 <版本中调用)来控制行为,该行为可以在特征中覆盖。ignore
像这样:
transient do # use `ignore` in factory bot < 5.0
with_callback_behavior { false }
end
after(:build) do |user, vars|
if vars.with_callback_behavior
puts "behavior for trait after build."
else
puts "behavior for main main after build."
end
end
trait :with_callbacks do
with_callback_behavior { true }
end
当然,这意味着
build :user, :with_callbacks
#=> "behavior for trait after build."
与
build :user, with_callback_behavior: true
#=> "behavior for trait after build."
评论
before/after