Search code examples
ruby-on-railsrspec-rails

RSpec stub object method with variable


Testing out a helper and I've run into an issue.

I have a scope on a model: Task.due_within(days)

And this is referenced in a helper:

module UsersHelper
  ...
  def show_alert(tasks, properties, user)
    pulse_alert(tasks, properties) ||
      tasks.due_within(7).count.positive? ||
      tasks.needs_more_info.count.positive? ||
      tasks.due_within(14).count.positive? ||
      tasks.created_since(user.last_sign_in_at).count.positive?
  end
  ...
end

So I'm testing with stubs for tasks, properties, and user:

RSpec.describe UsersHelper, type: :helper do
  describe '#show_alert' do
    it 'returns true if there are tasks due within 7 days' do
      tasks = double(:task, due_within: [1, 2, 3, 4], past_due: [])
      properties = double(:property, over_budget: [], nearing_budget: [])
      user = double(:user)

      expect(helper.show_alert(tasks, properties, user)).to eq true
    end

    it 'returns true if there are tasks due within 14 days' do
      # uh oh. This test would be exactly the same as above.
    end
  end
end

This passes, but when I went to write the test for it 'returns true if there are tasks due within 14 days, I realized that my double(:task, due_within: []) doesn't interact with the variable provided to the method.

How can I write a stub that cares about the variable provided to the method?

Obviously this doesn't work:

tasks = double(:task, due_within(7): [1, 2], due_within(14): [1, 2, 3, 4])

Solution

  • To handle the different cases, could you try something like this?

    allow(:tasks).to receive(:due_within).with(7).and_return(*insert expectation*)
    allow(:tasks).to receive(:due_within).with(14).and_return(*insert expectation*)
    

    Since you are testing the show_alert method, you might want to isolate your test to the show_alert method alone, i.e., mock due_within's return value as above. The functionality of due_within would be handled in a separate test case.