Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = '[email protected]'
    assert_empty Owner
    post '/owners', owner: {email: email}
    puts last_response.status
    refute_empty Owner

  end

  def test_other
    email = '[email protected]'
    get '/owners', owner: {email: email}
  end
end

```

like image 948
Peter Saxton Avatar asked Nov 27 '25 04:11

Peter Saxton


1 Answers

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 = '[email protected]'
    assert_empty Owner
    post '/owners', owner: {email: email}
    puts last_response.status
    refute_empty Owner

  end

  def test_other
    email = '[email protected]'
    get '/owners', owner: {email: email}
  end
end
like image 73
Peter Saxton Avatar answered Nov 28 '25 18:11

Peter Saxton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!