Ruby on rails 带变量的RSpec存根对象方法

Ruby on rails 带变量的RSpec存根对象方法,ruby-on-rails,rspec-rails,Ruby On Rails,Rspec Rails,在测试助手时,我遇到了一个问题 我在模型上有一个作用域: 任务。到期日(天) 这在助手中引用: module UsersHelper ... def show_alert(tasks, properties, user) pulse_alert(tasks, properties) || tasks.due_within(7).count.positive? || tasks.needs_more_info.count.positive? ||

在测试助手时,我遇到了一个问题

我在模型上有一个作用域:
任务。到期日(天)

这在助手中引用:

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
因此,我正在测试
任务
属性
用户
的存根:

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
这是通过的,但是当我为
编写测试时,如果在14天内有任务到期,它将返回true
,我意识到我的
double(:task,due_inthe:[])
不会与提供给方法的变量交互

如何编写关心提供给方法的变量的存根? 显然,这是行不通的:

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

为了处理不同的案件,你能试试这样的吗

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方法,即如上所述的mock due_in的返回值。due_的功能将在单独的测试用例中处理。

@Jessler FTW!谢谢是的,
Task.due_in(days)
是一个模型范围,在
spec/models/Task\u spec.rb
中进行了测试,这就是为什么我要保留响应。