带变量的RSpec存根对象方法

时间:2018-07-01 17:24:03

标签: ruby-on-rails rspec-rails

测试一个帮助程序,我遇到了一个问题。

我对模型有一个范围: Task.due_within(days)

这在一个助手中被引用:

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

所以我正在用taskspropertiesuser的存根进行测试:

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

这通过了,但是当我去为it 'returns true if there are tasks due within 14 days编写测试时,我意识到我的double(:task, due_within: [])与提供给该方法的变量没有相互作用。

我该如何编写一个存根于方法提供的变量的存根?

显然这不起作用:

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

1 个答案:

答案 0 :(得分:1)

要处理不同的情况,您可以尝试这样的事情吗?

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

由于您正在测试show_alert方法,因此您可能希望将测试仅与show_alert方法隔离,即模拟上述的due_within的返回值。 Due_within的功能将在单独的测试用例中处理。