Taking Screenshots

Taking a screenshot of the browser when a step fails can help you diagnose failures quicker. These screenshots can be embedded directly into an HTML report. The trick is to set up an After hook, as described in Using Hooks. Try adding the following code to a new file in features/support/screenshots.rb:

capybara/11/features/support/screenshots.rb
 
After(​'@javascript'​) ​do​ |scenario|
 
if​(scenario.failed?)
 
page.driver.browser.save_screenshot(​"html-report/​#{scenario.__id__}​.png"​)
 
embed(​"​#{scenario.__id__}​.png"​, ​"image/png"​, ​"SCREENSHOT"​)
 
end
 
end

We can take screenshots only when there is a browser, which is why we tagged the hook with @javascript. A hook can receive an optional argument that gives us a reference to the current scenario object, and we ask it if it’s failed so that we don’t take screenshots for passing scenarios.

Then we get an access to Selenium’s browser object by calling page.driver.browser. Keep in mind that it’s only Capybara’s Selenium driver that has a browser accessor. We’re safe since the tag makes sure this happens only when we’re running Selenium. We’re calling the save_screenshot method from Selenium to save the screenshot, and we’re using the scenario object’s __id__ as an identifier for the image file. (In Ruby, all objects have a unique __id__.)

After saving the object, we are calling the embed method, which takes three arguments—file_name, mime_type, and label. Cucumber will forward this to the active formatters, which will embed a reference to the file into the report. It’s actually only the HTML formatter that will take any action here. The other formatters will just ignore it.

Let’s make a little change to our code to provoke a failure so we can see the screenshot. Let’s reverse the results from the search in app/model/message.rb:

capybara/11/app/models/message.rb
 
class​ Message < ActiveRecord::Base
 
belongs_to :user
 
 
def​ self.like(content)
 
content.nil? ? [] : where([​'content LIKE ?'​, ​"%​#{content}​%"​]).reverse
 
end
 
attr_accessible :content, :user_id
 
end

Before we run Cucumber again, we have to create the output folder where the images will be written:

 
$ ​mkdir html-report

Now we can run Cucumber with the HTML formatter:

 
$ ​bundle exec cucumber --format html --out html-report/index.html

Try opening the generated HTML file in your browser. You should see a SCREENSHOT link for one of the two failing scenarios. The other failing scenario doesn’t have a screenshot, since it was running with the headless Rack driver.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.136