【问题标题】:How to test an if-condition not been excuted?如何测试未执行的 if 条件?
【发布时间】:2021-02-08 19:12:13
【问题描述】:

我是 Rspec 的新手。我有这样的代码:

if @context.persona == :system && @context.scopes&.include?(SEARCH_SCOPE)
  return <something>
end

我想编写一个单元测试来确认@context.persona 不是:system 时@context.scopes&amp;.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 == :systemfalse,因此永远不会到达@context.scopes&amp;.include?(SEARCH_SCOPE)。我不确定这个let(:persona) { :system } 应该做什么,但是如果不了解context 在测试中是什么,它将很难提供帮助。

标签: ruby-on-rails ruby rspec


【解决方案1】:

不是直接回答您的问题,而是您陷入了测试实现而不是行为的陷阱。不要那样做。

你的测试不应该关心这个:

expect(context).not_to have_received(:scopes)

相反,您的测试应该只做这样的事情:

context 'when persona is system and scopes includes SEARCH_SCOPE' do
  let(:persona) { :system }
  let(:scopes) { ... }
  
  it 'returns <something>' do
     expect(the_method_being_invoked).to eq(<something>)
  end
end

context 'when persona is not system' do
  let(:persona) { :user }
  let(:scopes) { ... }
  
  it 'returns <something-else>' do
     expect(the_method_being_invoked).to eq(<something-else>)
  end
end

context 'when scopes is empty' do
  let(:persona) { :user }
  let(:scopes) { nil }
  
  it 'returns <something-else>' do
     expect(the_method_being_invoked).to eq(<something-else>)
  end
end

为什么?因为当您重构代码并且实现发生变化时,您不希望规范开始失败,除非行为也发生了变化。

您通常甚至应该能够在编写方法之前编写测试 - 因此不知道其实现细节。

【讨论】:

  • 注意:对不起,我的规范定义有点模糊,但我不得不留下很多空白。如果原始示例更完整,那么我的答案将同样完整。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2011-05-19
相关资源
最近更新 更多