#257 Request Specs and Capybara
Request specs in RSpec are a great way to ensure the entire application stack is working properly. Here I also show how to use capybara with integrated JavaScript testing using Selenium.
- Download:
- source codeProject Files in Zip (131 KB)
- mp4Full Size H.264 Video (22.3 MB)
- m4vSmaller H.264 Video (14.8 MB)
- webmFull Size VP8 Video (39.1 MB)
- ogvFull Size Theora Video (31.3 MB)
Resources
- rspec-rails
- Capybara
- Database Cleaner
- Episode 155: Beginning with Cucumber
- Episode 156: Webrat
- Episode 187: Testing Exceptions
bash
bundle
rails g rspec:install
rails g integration_test task
rake spec:requests
bundle rails g rspec:install rails g integration_test task rake spec:requests
Gemfile
group :development, :test do
gem 'rspec-rails'
gem 'capybara', :git => 'git://github.com/jnicklas/capybara.git'
gem 'launchy'
gem 'database_cleaner'
end
# spec/requests/tasks_spec
describe "Tasks" do
describe "GET /tasks" do
it "displays tasks" do
Task.create!(:name => "paint fence")
visit tasks_path
page.should have_content("paint fence")
end
it "supports js", :js => true do
visit tasks_path
click_link "test js"
page.should have_content("js works")
end
end
describe "POST /tasks" do
it "creates task" do
visit tasks_path
fill_in "New Task", :with => "mow lawn"
click_button "Add"
# save_and_open_page
page.should have_content("Successfully added task.")
page.should have_content("mow lawn")
end
end
end
group :development, :test do gem 'rspec-rails' gem 'capybara', :git => 'git://github.com/jnicklas/capybara.git' gem 'launchy' gem 'database_cleaner' end # spec/requests/tasks_spec describe "Tasks" do describe "GET /tasks" do it "displays tasks" do Task.create!(:name => "paint fence") visit tasks_path page.should have_content("paint fence") end it "supports js", :js => true do visit tasks_path click_link "test js" page.should have_content("js works") end end describe "POST /tasks" do it "creates task" do visit tasks_path fill_in "New Task", :with => "mow lawn" click_button "Add" # save_and_open_page page.should have_content("Successfully added task.") page.should have_content("mow lawn") end end end
spec_helper.rb
require 'capybara/rspec'
RSpec.configure do |config|
# ...
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
require 'capybara/rspec' RSpec.configure do |config| # ... config.use_transactional_fixtures = false config.before(:suite) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
tasks/index.html.erb
<%= link_to_function "test js", '$(this).html("js works")' %>
<%= link_to_function "test js", '$(this).html("js works")' %>
