Testing Private Controller Methods in Rails
class FooController < ApplicationController private def is_awesome?(unicorns) unicorns.awesome == 'DEFINITELY' end end class FooControllerTest < ActionController::TestCase should 'return true when unicorns are awesome' @unicorn = Unicorn.new(awesome: 'DEFINITELY') assert_true @controller.send(:is_awesome?, @unicorn) end end
Yesterday I wrote two private methods to a controller that I was working on and, failing on doing TDD, I wrote the tests today. I actually ran into a few issues because, originally, I was not passing anything to my methods. The methods were just taking instance variables that were defined in the new method that was calling my functions. Works in practice, but when I wanted to test just these methods, I could not get them to read the instance variable without calling the whole new method. End result after trying a few other things? Just passing the variable to the private method (as seen above). Still works when called in the new method, but is also much easier to test. Success!