Functional test for the private rails controller

I have my own method in my controller. which is used for some database updates. I call this method from another controller method. and it works great.

But when I try to write a test case for this method, then it turns off when accessing (session variable and parameters) in my functional, all other methods work fine, is the problem only in the private method?

In my installation method in a functional test, I also establish a session.?

+3
source share
3 answers

You should avoid testing private methods. The β€œgoal” behind public / private / protected methods is to encapsulate logic and simplify changing parts of your code without worrying about how one function or class interacts with another.

If you still feel the need to test your personal methods, there are problems. I found this utility function through the Jay Field blog :

class Class
  def publicize_methods
    saved_private_instance_methods = self.private_instance_methods
    self.class_eval { public *saved_private_instance_methods }
    yield
    self.class_eval { private *saved_private_instance_methods }
  end
end

Check out the usage data link for a quick and easy way to do what you want to do.

+3
source

I like the offer of Damien Wilson . I am in my second statement that you "should avoid testing private methods." If necessary, I declare a public version of the method:

class FooTest < Test::Unit::TestCase
  Foo.class_eval do
    def public_bar(*args, &block)
      private_bar(*args, &block)
    end
  end

  def test_bar
    assert_equal 42, Foo.new.public_bar
  end
end
+1

, () ?

class Controller

protected
  def your_private_method
    ...
  end

end


class SubclassForTest < Controller

  def testwrapper
    your_private_method
  end

end
0

Source: https://habr.com/ru/post/1743185/


All Articles