Cucumber + Capybara + show me the page with the CSS stylesheets

Posted by ZedTuX 0n R00t on May 18, 2014

The first thing I was missing with Cucumber was the page style when using the show me the page step.

Looking to a black and white page is confusing at the beginning and is a real problem when what you’d like to test is composed of CSS divs.

Fix it !

Alright, today was the last day I was accepting to work this way ! :-)

Doing an inpect of the page headers we can see that the stylesheet path is /assets/application.css.

Capybara preparation

By default, Capybara is creating the path tmp/capybara/ and the Capybara method save_and_open_page will use this path to save the HTML files on the disk.

We have to change this, and I will explain why after. Open the features/env.rb file and add the following line:

Capybara.save_and_open_page_path = 'tmp/'

Now the Capybara method save_and_open_page will save the HTML files directly in the tmp/ folder so that we have to move back to one level instead of two in order to access the public/ folder..

Compile the assets

We have to create this application.css file. Rails provide the rake assets:precompile rake task to do so.

If you use it as is you will have an assets folder created in the public folder, and the files inside have a fingerprint:

$ tree public/assets
├── application-337f30378012a34fd8a4a70091aa8312.js
├── application-337f30378012a34fd8a4a70091aa8312.js.gz
├── application-466635608dec4e35aa69cce2fd23b0fe.css
├── application-466635608dec4e35aa69cce2fd23b0fe.css.gz

In order to have this fingerprint in the show me the page output file, we have to change the config/environments/test.rb file and add at the end the following lines:

config.assets.digest = true
config.assets.prefix = '../public/assets/'

The first line will force stylesheet_link_tag to use the file fingerprint. The second line will force the stylesheet_link_tag helper to move back of one level (from the tmp/ folder) and then go to the public/assets/ folder where the compiled assets by assets:precompile are stored.

Now execute the assets:precompile rake task:

RAILS_ENV=test rake assets:precompile


Now when you will execute the show me the page cucumber step, the page will be opened in your browser with the normal style ! :-D