rubysinatraminitestpadrinorack-test

testing padrino post methods are stopped by csrf


I have a padrino controller with a single post method and a single get method. I can use rack-test to test the get method but not the post method. When I am testing the request returns 403. I think this is because of padrino's built in csrf protection because when I comment out the line with set :protect_from_csrf, true I can test the post route. Obviously I don't want to comment out this line as csrf is useful. How can I get temporary access to test these routes for the purpose of testing?

Controller

SailPowerCourses::Admin.controllers :owners do

  get :index do
    puts 'hello'
  end

  post :index do
    puts params
  end

end

Test

class OwnersControllerTest < MiniTest::Test

  def setup
    app SailPowerCourses::Admin
  end

  def test_creates_an_owner
    email = 'test@example.com'
    assert_empty Owner
    post '/owners', owner: {email: email}
    puts last_response.status
    refute_empty Owner

  end

  def test_other
    email = 'test@example.com'
    get '/owners', owner: {email: email}
  end
end

```


Solution

  • When setting up an app in minitest you can use a block to access and change settings. such as csrf protection. I found the best solution to be the following. in test_config.rb I set up a version of the app with csrf protection off.

    class OwnersControllerTest < MiniTest::Test
    
      def setup
        app SailPowerCourses::Admin do
          set :protect_from_csrf, false
        end
      end
    
      def test_creates_an_owner
        email = 'test@example.com'
        assert_empty Owner
        post '/owners', owner: {email: email}
        puts last_response.status
        refute_empty Owner
    
      end
    
      def test_other
        email = 'test@example.com'
        get '/owners', owner: {email: email}
      end
    end