0

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])

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@jesslers FTW! Thanks!
And, yes, Task.due_within(days) is a model scope, tested in spec/models/task_spec.rb, which is why I'm stubbing the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.