Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: Stub private method

I try to test a class with RSpec2, that has some private methods, which are called from some public methods. I test the public methods with

@foo.should_receive(:start_training).exactly(2).times 

if they are called and how often. My problem is, that this approach doesn't work with private methods. So, is there any way to use sth like @foo.send(:private_method) in combination with should_receive? Or any other syntax?

like image 579
23tux Avatar asked Feb 20 '13 18:02

23tux


People also ask

What is stub in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.

Can you test private methods Ruby?

Testing private methods directly It's all about using the send method to call the private method directly. So you call it like any other public method and voilà, your test is done.

Is it OK to test private methods?

The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.

How do I mock a method in RSpec?

Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.


1 Answers

should_receive(:method) works whether the visibility of :method is public or private.

like image 122
Justin Aiken Avatar answered Sep 19 '22 13:09

Justin Aiken