Rspec测试中使用模拟技术对静态方法和非静态方法进行测试

8

我有一个这样的方法:

def self.method
  #API CALL
end

我正在为调用这个静态方法的控制器方法编写测试。代码如下:

it 'update order to confirmed' do
    Order.should_receive(:process_payment).and_return({})
    sign_in user
    attributes = FactoryGirl.attributes_for(:order, :valid_order)
    patch :confirm_order, params: { id: order.id, order: attributes }
    order.reload
    expect(order.confirmed).to eq true
end

这个方法之前一直是静态的并且一直工作正常。但我现在需要将它改为非静态的,结果测试失败了。

现在在我的控制器中,我调用该方法的方式如下:

Order.new.process_payment(@order)

问题可能出在我的模拟数据上,但我不知道该如何解决。有没有办法让我的模拟数据适应这个新格式呢?

2个回答

5
您可以使用allow_any_instance_of方法:
allow_any_instance_of(Order).to receive(:process_payment).and_return({})

2
allow_any_instance_of已经被弃用,应该替换为allow这里有一些示例。 - Thiago Petrone

0

Igor的答案很好。我也成功地让它像这样工作:

Order.any_instance.should_receive(:process_payment).and_return({})

1
提醒一下,这是使用 Object.any_instance 的旧语法,而现代的语法是 allow_any_instance_of。以下是文档链接:https://relishapp.com/rspec/rspec-mocks/v/3-9/docs/old-syntax/any-instance - CTS_AE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接