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
appis an instance ofActionDispatch::Integration::Session, which includesActionDispatch::TestProcessand therefore has a#sessionmethod that'll supply the authenticity token, once you've woken it up with a request.We can then use this via the
app::posthelper, itself a simple wrapper forapp's own#processmethod, 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: { ... }.