Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 893
Mark Kadlec Avatar asked Oct 08 '15 16:10

Mark Kadlec


People also ask

How do I know if a method was called RSpec?

You can check a method is called or not by using receive in rspec.

What does RSpec describe do?

The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.

Does RSpec clean database?

I use the database_cleaner gem to scrub my test database before each test runs, ensuring a clean slate and stable baseline every time. By default, RSpec will actually do this for you, running every test with a database transaction and then rolling back that transaction after it finishes.


2 Answers

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!

like image 189
Kryptman Avatar answered Sep 28 '22 05:09

Kryptman


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

like image 40
farith Avatar answered Sep 28 '22 07:09

farith