【发布时间】:2021-02-08 19:12:13
【问题描述】:
我是 Rspec 的新手。我有这样的代码:
if @context.persona == :system && @context.scopes&.include?(SEARCH_SCOPE)
return <something>
end
我想编写一个单元测试来确认@context.persona 不是:system 时@context.scopes&.include?(SEARCH_SCOPE) 没有被执行。这是我写的:
context 'when persona is system' do
let(:persona) { :system }
it 'checks the scope' do
allow(context).to receive(:scopes)
expect(context).to have_received(:scopes)
end
end
context 'when persona is not system' do
let(:persona) { :user }
it 'checks the scope' do
allow(context).to receive(:scopes)
expect(context).not_to have_received(:scopes)
end
end
第二个测试通过了,但第一个测试失败了:
Failure/Error: expect(context).to have_received(:scopes)
(Double (anonymous)).scopes(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
有人可以帮我吗?我之前用谷歌搜索过,但没有看到任何有用的信息。如有重复请见谅。
【问题讨论】:
-
很可能
@context.persona == :system是false,因此永远不会到达@context.scopes&.include?(SEARCH_SCOPE)。我不确定这个let(:persona) { :system }应该做什么,但是如果不了解context在测试中是什么,它将很难提供帮助。
标签: ruby-on-rails ruby rspec