Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to set a header to all tests using Minitest

.Hi. I have this API, and a custom header which is required to be passed in all requests to any controller. In Minitest, I should do @request.headers['Custom-Header'] = 'Custom Value' in every single test. Well, it happens I have many controllers, and this code is being repeated at the top describe block in each file.

I was trying to figure some way to make this DRYer. I even tried:

module Minitest::CustomHeaderSetup
  def before_setup
    super
    @request.headers['Custom-Header'] = 'Custom Value' if @request.present?
  end

  Minitest::Test.send(:include, self)
end

But @request doesn't exist at this moment. Any thoughts? Thanks!

like image 257
Jesse Mignac Avatar asked Oct 08 '15 19:10

Jesse Mignac


1 Answers

Solved!

Minitest::Test.send(:include, self) applies that code to every single test file, not only controller tests. So, what should be actually done is:

module Minitest::CustomHeaderSetup
  def before_setup
    super
    @request.headers['Custom-Header'] = 'Custom Value'
  end
end

And to those controller test files we want to behave like this, we should add:

include Minitest::CustomHeaderSetup

UPDATE

This would automatically set the custom header to all your controller tests.

module Minitest::CustomHeaderSetup                                                       
  def before_setup
    super
    @request.headers['Custom-Header'] = 'Custom Value'
  end

  ActionController::TestCase.send(:include, self)
end
like image 88
Jesse Mignac Avatar answered Oct 20 '22 20:10

Jesse Mignac