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?
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.
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.
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.
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.
should_receive(:method)
works whether the visibility of :method
is public or private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With