[英]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的返回值。 due_within的功能將在單獨的測試用例中處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.