dimanche 8 mai 2016

How to include URL helpers in Minitest tests in a DRY way

I'm writing test_helper.rb to require in my minitest tests and DRY up some code.

Here is one of my functional tests:

require 'test_helper'
class UserControllerTest < ActionController::TestCase
  def test_something
    get :index
    assert_redirected_to new_user_session_path
  end
end

This does not seem work when I try to include the URL helpers this way (method 1):

module TestBase
  include ActionDispatch::Routing::UrlFor
  include Rails.application.routes.url_helpers
  include FactoryGirl::Syntax::Methods
  include Warden::Test::Helpers
  include MiniTest::Assertions
  # ... other things
end

class ActionController::TestCase
  include TestBase
  include Devise::TestHelpers
  # ... other things
end

But this does work (method 2):

module TestBase
  include FactoryGirl::Syntax::Methods
  include Warden::Test::Helpers
  include MiniTest::Assertions
  # ... other things
end

class ActionController::TestCase
  include TestBase
  include Devise::TestHelpers
  include ActionDispatch::Routing::UrlFor
  include Rails.application.routes.url_helpers
  # ... other things
end

Another working option is to just include the URL helpers directly in the functional test (method 3):

require 'test_helper'
include ActionDispatch::Routing::UrlFor
include Rails.application.routes.url_helpers

class UserControllerTest < ActionController::TestCase
  def test_something
    get :index
    assert_redirected_to new_user_session_path
  end
end

My question is: why doesn't the first method work? What are UrlFor and url_helpers doing that the child classes don't gain access to the URL helper methods using the first method? I'm sure this has something to do with how inheritance works (or doesn't work) with modules, but I don't know why it's happening.

Can anyone explain to me what's happening in the three different methods?

Aucun commentaire:

Enregistrer un commentaire