RSpec 带变量的存根对象方法
RSpec stub object method with variable
正在测试助手,我 运行 遇到了问题。
我有一个模型的范围:
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
所以我正在使用 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
这通过了,但是当我去为 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])
为了处理不同的情况,你能试试这样吗?
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 的 return 值如上。 due_within 的功能将在单独的测试用例中处理。
正在测试助手,我 运行 遇到了问题。
我有一个模型的范围:
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
所以我正在使用 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
这通过了,但是当我去为 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])
为了处理不同的情况,你能试试这样吗?
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 的 return 值如上。 due_within 的功能将在单独的测试用例中处理。