How to specify a private method

I have a model with a private method that I would like to specify with RSpec,
how do you usually do this? Are you just checking the private call method?
or also specify private? if so, how are you?

+44
ruby-on-rails rspec
Nov 11 2018-10-11
source share
3 answers

I always take this approach: I want to test the public API that my class provides.

If you have private methods, you only call them from public methods that you publish to other classes. Therefore, if you verify that these public methods work as expected under any conditions, you have also proven that the private methods that they use also work.

I admit that I came across some particularly complex private methods. In this extreme case, you want to test them, you can do this:

@obj.send(:private_method) 
+106
Nov 11 '10 at 12:52
source share
β€” -

For private methods that require code coverage (temporarily or permanently), use the rspec-context-private gem to temporarily publish private methods in context.

 gem 'rspec-context-private' 

It works by adding a general context to your project.

 RSpec.shared_context 'private', private: true do before :all do described_class.class_eval do @original_private_instance_methods = private_instance_methods public *@original_private_instance_methods end end after :all do described_class.class_eval do private *@original_private_instance_methods end end end 

Then, if you pass :private as metadata to the describe block, private methods will be public in this context.

 class Example private def foo 'bar' end end describe Example, :private do it 'can test private methods' do expect(subject.foo).not eq 'bar' end end 
+6
May 24 '14 at 17:29
source share

If you want to check expectations on a private method, the accepted answer really doesn't work (at least not the one I know about, so I'm open to fixing at this point). What I did is even more dirty - in the test itself, simply expose the method, overriding it:

 def object_to_test.my_private_method super end 

Powered by Ruby 1.8, cannot comment on any new versions.

0
04 Oct '17 at 23:14
source share



All Articles