如何使用 Rails 4.2.3 在我的 FactoryGirl 工厂中模拟回调?

How do I mock a callback in my FactoryGirl factory, using Rails 4.2.3?

提问人:Dave 提问时间:6/17/2022 更新时间:6/17/2022 访问量:53

问:

我正在使用 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.

当我运行所有测试时,其中

创建(:用户)

我还有什么方法可以在工厂中模拟这个回调?

Ruby-on-Rails Ruby-On-Rails-4 回调 模拟 工厂

评论

0赞 Jake Worth 6/17/2022
看起来在测试(或块)之外不支持支持的模拟功能。to receiveitspecify
0赞 ajsharma 6/17/2022
它需要在工厂里吗?你能在构建对象后在测试中模拟它吗?
0赞 Dave 6/17/2022
嗨,@ajsharma,有大量的测试。修改每个是可能的,但非常耗时。我觉得在构建工厂对象时应该有一种全局的方法来进行这种模拟,但不确定这是如何完成的。

答:

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)没有被调用的情况。谢谢你!