Monday, April 27, 2009

Using webrat for integration testing

What is webrat

Webrat lets you quickly write expressive and robust acceptance tests for a rails application.

How Webrat is different from default rails integration test

1. Rails default integration testing is nothing more than a series of functional tests. But in webrat you can actually do actions in pages. Here is a scenario for login.

visit('/')
fill_in('email', :with => user.email)
fill_in('password', :with => '1234')
click_button('login')

2. With webrat you can test user experience by filling in the text boxes, clicking the buttons etc.

3. Use webrat API for Browser Simulator and real Selenium tests using Webrat::Selenium when necessary (eg. for testing AJAX interactions).

4. Supports popular test frameworks: RSpec, Cucumber, Test::Unit and Shoulda

Installing webrat

gem install nokogiri
gem install webrat

In test_helper.rb add,

require "webrat"

Webrat.configure do |config|
 config.mode = :rails
end

For more information please visit http://github.com/brynary/webrat/tree/master

Some Tips

You can check something like, if your desired dropdown select option is currently selected or not using assert_select.

Let me show you the expected html to test

<select name="user[user_type_id]" id="user_user_type_id">
 <option selected="selected" value="1">Shipper</option>
 <option value="2">Transporter</option>
</select>

Here we want to test of Shipper is selected or not.

So the test code can be

test 'signup form with shipper' do
 visit('/')
 click_link('Signup as Shipper')
 assert_selected_option('user_user_type_id', 'Shipper')
end

def assert_selected_option(select_id, selected_text)
 assert_select("##{select_id} option[selected=selected]", selected_text)
end

This is how you can test contents of html.

Resources

http://github.com/brynary/webrat/tree/master

http://www.slideshare.net/brynary/webrat-rails-acceptance-testing-evolved

http://cheat.errtheblog.com/s/webrat/

No comments: