如何使用Rspec检查方法是否存在?

Mar*_*lec 6 rspec ruby-on-rails

我想写一个很好的干净检查方法是否存在:

expect(subscriber.respond_to?(:fake_method)).to be(true)    <-- This fails (as expected)

expect(subscriber).respond_to?(:fake_method)                <-- This passes, why?
Run Code Online (Sandbox Code Playgroud)

fake_method不存在,但是当我使用第二个约定时,我的测试通过了.

有任何想法吗?

Kry*_*man 6

我相信我有答案。第二种约定不起作用,因为根据文档,匹配器有所不同:

https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/respond-to-matcher

您应该尝试:

expect(subscriber).to respond_to(:fake_method) 
Run Code Online (Sandbox Code Playgroud)

干杯!