x6iae
x6iae

Reputation: 4164

how to correctly use stub for testing in rspec

So, I have a method in a class as follow:

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

And I want to spec it. So, I just wrote an RSpec test to test it as follow:

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

And this is working.

However, I began to wonder if this was a correct way of doing it. Like: am I sure that even if I stub the wrong ( probably inexistent ) method, and test for it, will it pass or fail?

I tried it, it passed

So, if later, the method name gets changed, there is no way for this test to detect that.

So, here is the question: How can I be sure that a RSpec stubbed method is actually existent in a code?

Upvotes: 1

Views: 520

Answers (1)

user419017
user419017

Reputation:

Here's how I'd set it up. Might help..

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

Upvotes: 2

Related Questions