我可以得到 RSpec `expect().to(raise_error))` 来打印它不应该收到的 return 值吗?
Can I get RSpec `expect().to(raise_error))` to print the return value it shouldn't have received?
我正在为异常情况编写一些 Rspec 测试。我习惯于用其他语言编写与此等效的内容:
it 'explodes on something bad' do
actual = funny_function()
raise "This should have thrown, but received #{actual}"
rescue StandardError => e
expect(e).to(be_instance_of(MyLovelyError))
expect(e.message).to(eq('You are delightfully whimsical'))
end
因为我发现它很有用,当测试失败时,报告立即提供信息,而不是被迫在调试器中重新运行测试。
Rspec 的特殊异常语法吞没了实际值,只是说“...但没有引发任何问题”,这有点弱。我可以做到...
def expect_raise
expect { raise("Expected failure, but actual=#{yield}") }
end
expect_raise { funny_function() }.to(raise_error(MyLovelyError, 'You are delightfully whimsical'))
但这感觉很笨拙:在这种情况下,似乎 Rspec 应该有某种装饰器来显示 'actual'。我浏览了文档,但没有发现任何东西。
有人知道吗?
库存 rspec 匹配器中没有任何内容。
但是 raise_error
只是一个匹配器,您最好的机会是编写自己的匹配器,这非常容易做到。
https://relishapp.com/rspec/rspec-expectations/v/2-11/docs/custom-matchers
https://relishapp.com/rspec/rspec-expectations/v/2-11/docs/custom-matchers/define-matcher
您还可以查看 raise_error
的实现以获取灵感:
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/raise_error.rb#L51:L58
我正在为异常情况编写一些 Rspec 测试。我习惯于用其他语言编写与此等效的内容:
it 'explodes on something bad' do
actual = funny_function()
raise "This should have thrown, but received #{actual}"
rescue StandardError => e
expect(e).to(be_instance_of(MyLovelyError))
expect(e.message).to(eq('You are delightfully whimsical'))
end
因为我发现它很有用,当测试失败时,报告立即提供信息,而不是被迫在调试器中重新运行测试。
Rspec 的特殊异常语法吞没了实际值,只是说“...但没有引发任何问题”,这有点弱。我可以做到...
def expect_raise
expect { raise("Expected failure, but actual=#{yield}") }
end
expect_raise { funny_function() }.to(raise_error(MyLovelyError, 'You are delightfully whimsical'))
但这感觉很笨拙:在这种情况下,似乎 Rspec 应该有某种装饰器来显示 'actual'。我浏览了文档,但没有发现任何东西。
有人知道吗?
库存 rspec 匹配器中没有任何内容。
但是 raise_error
只是一个匹配器,您最好的机会是编写自己的匹配器,这非常容易做到。
https://relishapp.com/rspec/rspec-expectations/v/2-11/docs/custom-matchers
https://relishapp.com/rspec/rspec-expectations/v/2-11/docs/custom-matchers/define-matcher
您还可以查看 raise_error
的实现以获取灵感:
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/raise_error.rb#L51:L58