Skip to content
Discussion options

You must be logged in to vote

How can I test a form that has CSRF protection?

From the Mojolicious test suite, t/mojolicious/validation_lite_app.t:

use Mojo::Base -strict;

BEGIN { $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll' }

use Test::Mojo;
use Test::More;
use Mojolicious::Lite;

any '/forgery' => sub {
  my $c = shift;
  my $v = $c->validation;
  return $c->render unless $v->has_data;
  $v->csrf_protect->required('foo');
};

my $t = Test::Mojo->new;

subtest 'Correct CSRF token' => sub {
  # See also: https://docs.mojolicious.org/Mojolicious/Guides/Testing#Cookies-and-session-management
  my $token = $t->ua->get('/forgery')->res->dom->at('[name=csrf_token]')->val;
  $t->post_ok('/forgery' => form => {csrf_token => 

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@Wail75
Comment options

Answer selected by Wail75
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants