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 ofActionDispatch::Integration::Session
, which includesActionDispatch::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 forapp
's own#process
method, which documents the calling parameters.Putting all of those pieces together, in Rails 5 and later, we might write:
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:
and this should be revised to the new syntax, wrapping the parameters in
params: { ... }
.