RSpec 测试类方法调用实例方法 [英] RSpec test that a class method calls an instance method

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

问题描述

我想测试一个类方法是否调用了一个特定的实例方法.有没有办法做到这一点?这是我拥有的最好的,但它失败了.

I'm looking to test that a class method calls a specific instance method. Is there any way to do this? This is the best I've got, but it fails.

describe '#foo' do
  let(:job) { create :job }
  it 'calls job.bar' do
    job.should_receive(:bar)
    Job.foo
  end
end

我需要确保调用了正确的作业实例,而不仅仅是任何实例.感谢您的帮助.

I need to be sure that the right instance of job is called, not just any instance. I appreciate any help.

推荐答案

您可以在 .foo 获取实例的方法上使用存根.

You can use stubs on the method by which .foo gets the instance.

例如:

describe '.foo' do
  let(:job) { create :job }
  it 'calls job.bar' do
    Job.stub(:find).and_return job
    job.should_receive(:bar)
    Job.foo
  end
end

这样做是为了确保您期望调用方法的实例是 .foo 实际使用的实例.

What this does is ensures that the instance that you expect to have methods called on is the one that actually gets used by .foo.

您可以为此添加期望或参数匹配器,因此:

You can add expectations or argument matchers to this, so:

Job.should_receive(:find).with(job.id).and_return(job)

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

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