rspec 如何正确使用存根进行测试

how to correctly use stub for testing in rspec

所以,我在 class 中有一个方法如下:

def installation_backlog
  Api::Dashboards::InstallationsBacklog.new(operational_district_id, officer_id).backlog_tasks
end

我想详细说明一下。所以,我只是写了一个 RSpec 测试来测试它如下:

it "should call a new instance of InstallationsBacklog with the backlog_tasks method" do
  expect_any_instance_of(Api::Dashboards::InstallationsBacklog).to receive(:backlog_tasks)
  @installation_officer.installation_backlog # @installation_officer is a new instance of the container class.
end

这是有效的。

但是,我开始怀疑这是否是正确的做法。比如:我确定即使我对错误的(可能不存在的)方法进行存根并对其进行测试,它会通过还是失败?

我试过了,通过了

因此,如果稍后更改了方法名称,则此测试无法检测到。

所以,问题来了:我如何确定 RSpec 存根方法确实存在于代码中?

这是我的设置方式。可能有帮助..

let(:backlog) {
  double('Backlog', backlog_tasks: [])
}

before do
  allow(Api::Dashboards::InstallationsBacklog).to receive(:new).
    and_return(backlog)
end

it 'instantiates InstallationBacklog' do
  expect(Api::Dashboards::InstallationBacklog).to receive(:new).
    with(operational_district_id, officer_id)

  @installation_officer.installation_backlog
end

it 'calls backlog_tasks on instance of InstallationBacklog' do
  expect(backlog).to receive(:backlog_tasks)

  @installation_officer.installation_backlog
end