Here at PlataformaTec we like to use Capybara for acceptance tests. Recently we have discovered the custom selectors feature in Capybara and we would like to share with you how that feature helped us to improve our tests.
Sometimes we need to implement features that involves showing some ordered items to the user, like a ranking feature. The HTML for a feature like that could be:
<ol id="overall-ranking"> <% @top_users.each do |user| %> <li><%= user.name %></li> <% end %> </ol> |
The acceptance tests for this ranking could be written as follows:
scenario "The user can see an overall ranking" do Factory(:user, :name => "Hugo", :score => 5000) Factory(:user, :name => "Ozaki", :score => 3000) Factory(:user, :name => "João", :score => 4000) visit overall_ranking_path within("#overall-ranking") do find(:xpath, './/li[1]').text.should match("Hugo") find(:xpath, './/li[2]').text.should match("João") find(:xpath, './/li[3]').text.should match("Ozaki") end end |
Generally, I don’t like to see those XPath selectors inside my acceptance tests. And sometimes it can get really ugly! So, in order to improve our tests, we can create a custom selector with Capybara as follows:
# spec/spec_helper.rb RSpec.configure do |config| Capybara.add_selector(:li) do xpath { |num| ".//li[#{num}]" } end end |
After that, we can refactor our test as shown below:
scenario "The user can see an overall ranking" do Factory(:user, :name => "Hugo", :score => 5000) Factory(:user, :name => "Ozaki", :score => 3000) Factory(:user, :name => "João", :score => 4000) visit overall_ranking_path within("#overall-ranking") do find(:li, 1).text.should match("Hugo") find(:li, 2).text.should match("João") find(:li, 3).text.should match("Ozaki") end end |
If you wanna know more about Capybara’s custom selectors, check its README.
And you? Any tips about using Capybara or improving your acceptance/integration tests?
This entry was posted on Wednesday, February 9th, 2011 at 2:31 pm and is filed under English. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
-
Anonymous
-
http://blog.plataformatec.com.br/ josevalim
-
Anonymous
-
http://blog.plataformatec.com.br/ josevalim
-
http://carlosantoniodasilva.wordpress.com Carlos Antonio
-
Anonymous

All
English only
Em português apenas