提问人:Dave 提问时间:6/17/2022 更新时间:6/17/2022 访问量:53
如何使用 Rails 4.2.3 在我的 FactoryGirl 工厂中模拟回调?
How do I mock a callback in my FactoryGirl factory, using Rails 4.2.3?
问:
我正在使用 Rails 4.2.3。我的用户模型中有这个回调......
after_create :publish
…
def publish
Mymodule::Publisher.new_user(user: self, x_forward: {})
end
我想嘲笑这个回调
FactoryGirl.define do
…
factory :user do
after(:build) do |user|
allow(user).to receive(:publish)
end
但这会导致
The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported.
当我运行所有测试时,其中
创建(:用户)
我还有什么方法可以在工厂中模拟这个回调?
答:
1赞
Yurii Stefaniuk
6/17/2022
#1
你可以这样做:
FactoryGirl.define do
factory :user do
# ...
after(:build) do |user|
def user.publish
# and here you can stub method response if you need
end
end
end
end
评论
0赞
Dave
6/17/2022
谢谢,但这不起作用。直接在类中定义的方法不断被调用。
0赞
Yurii Stefaniuk
6/17/2022
奇怪。我在我的规格中使用了这种方法,它有效
0赞
Dave
6/17/2022
我的错,你是对的。我遇到了工厂after(:build)没有被调用的情况。谢谢你!
评论
to receive
it
specify