Joeri Timmermans

IT Consultancy
Kruisstraat 30 bus 002, 3120 Tremelo
+32 477 39 91 34
BE 0679.905.761

Testing file upload with custom hidden upload fields in Behat

Friday October 9, 2015 - Permalink - Tags: behat, custom, selenium, testing, jquery

I'm currently working on a big project at Intracto where they want a lot of fancy visuals and this turned into a mess when it came to write behat tests. This post will help you test fancy buttons that trigger a hidden file input field to upload something.

Our case

The upload button is there but the input field is hidden meaning that if you use the default function from the MinkContext that it will cry out saying the "Element is not currently visible and so may not be interacted with". Since we really want this tested I made a hack to solve our issue.

STEP 1: Create a custom context extending or including MinkContext

More info can be found http://docs.behat.org/en/latest/guides/4.contexts.html

STEP 2: Create your custom action

 * Attaches file to field with specified name.
 * @When /^(?:|I )attach the file "(?P<path>[^"]*)" to hidden field "(?P<field>(?:[^"]|\\")*)"$/
public function attachFileToHiddenField($field, $path)
    $field = $this->fixStepArgument($field);

    $javascript = "$('input[name=".$field."].hidden').removeClass('hidden').css('position', 'absolute');";

    $this->attachFileToField($field, $path);

In our case the input field had a hidden css class and was positioned far away. Since we know Jquery is available in out application we use Javascript to remove the hidden class and add position absolute so the element comes on stage. Then we run the default attachFileToField function.

STEP 3: Attach a file to it

Given I attach the file "picture.png" to hidden field "upload-file"

STEP 4: Benefit

comments powered by Disqus