1

As a part of my rails application I created a helper under ApplicationHelper that checks for devise generated errors and adds them to the flash[:error] hash.

  def devise_flash
    if controller.devise_controller? && resource && resource.errors.any?
      # modify flash
    end
  end

This helper gets called in the view layer (e.g. application.html.erb).

However, I can't really unit test this method because it relies on the controller instance to be a devise controller. I could test it by checking a view using assert_select that uses the helper to show the flash messages, but that feels weird.

Is this a symptom of bad design? Something else? Should I be looking for ways to stub out controller to unit test this function?

Adam Thompson
  • 3,278
  • 3
  • 22
  • 37
  • You can stub and test the helper method, see https://stackoverflow.com/questions/14402067/how-to-call-an-app-helper-method-from-an-rspec-test-in-rails – lacostenycoder May 01 '18 at 04:30
  • Although, why does it matter which controller action or resource? shouldn't any model validation error show some flash notification to the user? – lacostenycoder May 01 '18 at 07:44
  • @lacostenycoder yes if it contains devise errors. I'm really unsure if I am even testing this the correct way, it feels a bit like perhaps I'm testing internals rather than some API, like I either need to decompose or do a controller/view test rather than a unit test on this method. – Adam Thompson May 01 '18 at 15:55
  • 1
    the unit test should test the result of the method, not the internals. But why call this method from a helper at all if it depends on controller logic? We already trust devise to handle validations. Isn't that where the errors come from anyway? The point of TDD is to avoid logic in the wrong place anyway. – lacostenycoder May 01 '18 at 16:16
  • Due to the way rails set the flash, can't append to the flash before rendering so need to call it in the view layer. In this case it looks like it's just not worth unit testing. – Adam Thompson May 01 '18 at 18:50
  • Maybe have a look here https://stackoverflow.com/questions/4097932/devise-rails-how-to-remove-a-particular-flash-message-signed-in-successfully#4098154 – lacostenycoder May 01 '18 at 19:20

0 Answers0