1

Somewhere I have read that private methods aren't supposed to be tested. Your tests should only care about the real thing - your public API. If your public methods work, then the private ones they call will also work

So is it not necessary to test private methods, but consider below example

  private

  def valid_extension?(file_path)
    extension = file_type(file_path)
    extension.in?(%w(csv xls xlsx)) ? true : false
  end

the above private method returns whether the file extension is valid or not, so what if someone changes my private method like this

  private
  def valid_extension?(file_path)
    true
  end

it will always give me valid extension

So, is it not necessary to test private methods also.

Since we cannot access private method outside class, so how to test the private methods using rspec-rails.

chandradot99
  • 3,616
  • 6
  • 27
  • 45
  • Just like you mentioned, if you test public methods then the private methods are indirectly tested. For the most part, as long as you have an extensive set of tests for the public methods, some of your public method tests should fail given the change in the example that you provided, which you would then have to trace back to the private method causing the test to fail. However, if you have a particularly complex private method, sometimes that is worth writing a test for. – hypern Jun 23 '16 at 13:00
  • I always test anything that has logic complicated enough to fail. Whether it's private or not is not really something I worry about. For me it's all about isolation and simplification of my testing. – jaydel Jun 23 '16 at 20:58

1 Answers1

2

As per Rspec, Rails: how to test private methods of controllers? , you may use

@your_instance_name.instance_eval{ valid_extension }

Community
  • 1
  • 1
Tharsan Sivakumar
  • 6,351
  • 3
  • 19
  • 28