Mark Kadlec
Mark Kadlec

Reputation: 8440

How to check if a method exists using Rspec?

I want to write a nice clean check whether a method exists or not:

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

expect(subscriber).respond_to?(:fake_method)                <-- This passes, why?

The fake_method does not exist, but when I use the second convention, my test passes.

Any ideas?

Upvotes: 9

Views: 7193

Answers (2)

farith
farith

Reputation: 23

we can simply use expect(subscriber).not_to respond_to(:fake_method) for negative case.

Upvotes: 1

Kryptman
Kryptman

Reputation: 1016

I believe I have the answer. The second convention doesn't work because the matcher is different according to the documentation:

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

You should try with:

expect(subscriber).to respond_to(:fake_method) 

Cheers!

Upvotes: 15

Related Questions