Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test file download in Behat

Tags:

bdd

behat

mink

There is this new Export functionality developed on this application and I'm trying to test it using Behat/Mink. The issue here is when I click on the export link, the data on the page gets exported in to a CSV and gets saved under /Downloads but I don't see any response code or anything on the page.

Is there a way I can export the CSV and navigate to the /Downloads folder to verify the file?

like image 901
vijay pujar Avatar asked Jul 24 '14 09:07

vijay pujar


1 Answers

Assuming you are using the Selenium driver you could "click" on the link and $this->getSession()->wait(30) until the download is finished and then check the Downloads folder for the file.

That would be the simplest solution. Alternatively you can use a proxy, like BrowserMob, to watch all requests and then verify the response code. But that would be a really painful path for that alone.

The simplest way to check that the file is downloaded would be to define another step with a basic assertion.

/**
 * @Then /^the file ".+" should be downloaded$/
 */
public function assertFileDownloaded($filename) 
{
    if (!file_exists('/download/dir/' . $filename)) {
        throw new Exception();
    }
}

This might be problematic in situations when you download a file with the same name and the browser saves it under a different name. As a solution you can add a @BeforeScenario hook to clear the list of the know files.

Another issue would be the download dir itself – it might be different for other users / machines. To fix that you could pass the download dir in your behat.yml as a argument to the context constructor, read the docs for that.

But the best approach would be to pass the configuration to the Selenium specifying the download dir to ensure it's always clear and you know exactly where to search. I am not certain how to do that, but from the quick googling it seems to be possible.

like image 107
Ian Bytchek Avatar answered Sep 28 '22 00:09

Ian Bytchek