如何使用rspec存根函数调用?

时间:2021-02-09 20:23:11

The code I'm working on looks like:

我正在处理的代码如下:

class A
  def get_news

    when self.type = 'TypeA'
        param1 = 'a'
        param2 = 'b'
    else
        param1 = 'c'
        param2 = 'd'
    end

    @news ||= B.new.get_news(param1, param2)
  end
end

I would like to be able to test that the right parameters get passed to B#get_news. Do you know a way to stub the function call, so I can test that it gets called with the correct parameters instead of testing that a request gets made with the correct parameters?

我希望能够测试正确的参数传递给B#get_news。你知道一种存根函数调用的方法,所以我可以测试它是用正确的参数调用的,而不是用正确的参数测试请求吗?

I have spent some time on it and I can't figure out a way to do it.

我花了一些时间在上面,我无法找到一种方法来做到这一点。

In advance, thanks!

提前谢谢!

1 个解决方案

#1


0  

First stub out any_instance of B:

第一个存根b的any_instance:

B.any_instance.stubs(:get_news)

Then have the spec call your method. You can then verify that get_news was called using expect_any_instance_of:

然后让规范调用你的方法。然后,您可以使用expect_any_instance_of验证是否已调用get_news:

expect_any_instance_of(B).to receive(:get_news).with(..., ...)

Pass whatever values to with() you are expecting the get_news method to come along with.

将任何值传递给with(),你期望get_news方法随之而来。

#1


0  

First stub out any_instance of B:

第一个存根b的any_instance:

B.any_instance.stubs(:get_news)

Then have the spec call your method. You can then verify that get_news was called using expect_any_instance_of:

然后让规范调用你的方法。然后,您可以使用expect_any_instance_of验证是否已调用get_news:

expect_any_instance_of(B).to receive(:get_news).with(..., ...)

Pass whatever values to with() you are expecting the get_news method to come along with.

将任何值传递给with(),你期望get_news方法随之而来。