I am trying to write tests in Mojolicious for checking if an image attachment was sent correctly from a form.
I have a form containing <input type="file" name="image_upload" accept="image/*">
. In the controller I am checking if $self->req->upload('image_upload')->headers->content_type =~ /image/
. The tests, on the other side, send the image file as form => {image_upl => { content => 'abc', filename => 'x.png' }}
inside the post request. Running the application works well, but the check fails inside the testing code. I don't really understand how those headers are set, so that I can send a mock image inside the post request.
Here is the code:
#Router.
$if_admin->post('/attachment/:page_id/add')->name('on_attachment_add')
->to('attachment#on_add');
# Client side (Mojolicious template).
<%= form_for 'on_attachment_add' => { page_id => $self->stash('id') }
=> (method => 'POST') => (enctype => "multipart/form-data")
=> begin %>
<input type="file" name="image_upload" accept="image/*">
% end
# Controller (on_add)
my $self = shift;
my $image_file = $self->req->upload('image_upload');
if (!$image_file || $image_file->slurp eq "" || !$image_file->headers ||
!$image_file->headers->content_type ||
!($image_file->headers->content_type =~ /image/)) {
$self->render(
template => 'validation/invalid_data',
status => 400
);
}
# test.
$t->post_ok('/attachment/test_page/add' => form => {
image_upload => { content => 'aaa', filename => 'x.png' },
image_name => 'new_image.jpg'
})->status_is(200);
After looking here http://mojolicious.org/perldoc/Mojo/UserAgent/Transactor#tx I added 'Content-Type' => 'image/png'
to the hash reference in the form as such:
$t->post_ok('/attachment/test_page/add' => form => { image_upload =>
{ content => 'abc', filename => 'x.png', 'Content-Type' => 'image/png' },
image_name => 'new_image.jpg'
})->status_is(200);
This solved the problem.