Should I Test Private Methods Using Rspec

Should I test private methods using RSpec?

You can find an in-depth discussion of that very subject in these slides from a Sandi Metz talk.

https://speakerdeck.com/skmetz/magic-tricks-of-testing-railsconf

She says that you may test-drive your private methods if you like, but that the only test that you should worry about are the ones testing the public interface. Otherwise you may be coupling too tightly to implementation.

I think the point by toch, on splitting out service and value object and putting those under tests is also a good one if you are getting nervous about complex private methods that aren't tested.

Rspec, Rails: how to test private methods of controllers?

Use #instance_eval

@controller = AccountController.new
@controller.instance_eval{ current_account } # invoke the private method
@controller.instance_eval{ @current_account }.should eql ... # check the value of the instance variable

Rspec test of private model method in rails app

By definition, you are not allowed to call private methods from outside of the class because they are private.

Fortunately for you, you can do what you want if you use object.send(:my_vital_method) which skips the testing for method call restrictions.

Now, the bigger issue is that you really are making your object more brittle, because calling from outside like that may need implementation details that will get out of sync with the class over time. You are effectively increasing the Object API.

Finally, if you are trying to prevent tampering, then you are tilting at windmills -- you can't in Ruby because I can just trivially redefine your method and ensure that if my new method is called from your anti-tamper checking code, I call the original version, else I do my nefarious stuff.

Good luck.

How to test private helper(module) method in rspec

create a dummy class and access private method using .send(:private_method, args)

example

obj = Class.new { extend AppHelper }
obj.send(:sum, 1,2)

Test private method of controller with rspec

You can set your env variable like following:

request.env['HTTP_SESSIONTOKEN'] = "..."

For testing your private method:

controller.instance_eval{ authenticate }.should eql ...


Related Topics



Leave a reply



Submit