[英]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)
我在模型上有一个范围:
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
: 所以我正在测试存根的
tasks
, properties
和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. 这通过了,但是当我去编写测试时,
it 'returns true if there are tasks due within 14 days
,我意识到我的double(:task, due_within: [])
与提供给该方法的变量没有交互作用。
Obviously this doesn't work: 显然这是行不通的:
tasks = double(:task, due_within(7): [1, 2], due_within(14): [1, 2, 3, 4])
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, ie, mock due_within's return value as above. 由于您正在测试show_alert方法,因此您可能希望将测试仅与show_alert方法隔离,即,像上面那样模拟due_within的返回值。 The functionality of due_within would be handled in a separate test case.
due_within的功能将在单独的测试用例中处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.