RSpec:如何测试方法是否被调用? [英] RSpec: how to test if a method was called?

查看:42
本文介绍了RSpec:如何测试方法是否被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写 RSpec 测试时,我发现自己编写了很多看起来像这样的代码,以确保在测试执行期间调用了一个方法(为了论证,我们只能说我真的不能调用后查询对象的状态,因为方法执行的操作不容易看到效果).

When writing RSpec tests, I find myself writing a lot of code that looks like this in order to ensure that a method was called during the execution of a test (for the sake of argument, let's just say I can't really interrogate the state of the object after the call because the operation the method performs is not easy to see the effect of).

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
    called_bar = false
    subject.stub(:bar).with("an argument I want") { called_bar = true }
    subject.foo
    expect(called_bar).to be_true
  end
end

我想知道的是:还有比这更好的语法吗?我是否错过了一些时髦的 RSpec 很棒的东西,可以将上面的代码减少到几行?should_receive 听起来它应该这样做,但进一步阅读它听起来不像它所做的那样.

What I want to know is: Is there a nicer syntax available than this? Am I missing some funky RSpec awesomeness that would reduce the above code down to a few lines? should_receive sounds like it should do this but reading further it sounds like that's not exactly what it does.

推荐答案

it "should call 'bar' with appropriate arguments" do
  expect(subject).to receive(:bar).with("an argument I want")
  subject.foo
end

这篇关于RSpec:如何测试方法是否被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆