I am trying to use my rails console to call a public post method in my controller.
rails c
app.post '/servers/important_method'
This obviously gives me:
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
Is there any way to create a session and call that method?
EDIT: I could create a view and restart the production environment, but I'd like to avoid that.
The key here is recognising app
is an instance of ActionDispatch::Integration::Session
, which includes ActionDispatch::TestProcess
and therefore has a #session
method that'll supply the authenticity token, once you've woken it up with a request.
We can then use this via the app::post
helper, itself a simple wrapper for app
's own #process
method, which documents the calling parameters.
Putting all of those pieces together, in Rails 5 and later, we might write:
app.get ''
token = app.session[:_csrf_token]
app.post '/servers/important_method', params: { authenticity_token: token }
Note for older versions of Rails:
Since we're talking to the integration test API here, you may use similar forms in integration tests. When upgrading older Rails apps (v4 and earlier), you may find the following test code failing:
post '/servers/important_method', authenticity_token: token
and this should be revised to the new syntax, wrapping the parameters in params: { ... }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With