/learn-capybara

Getting Started with capybara, rspec, and capybara-webkit

Primary LanguageHTML

Getting Started with capybara

Learning how to use rspec, capybara and webkit with rails

1. Creating Project

=======================

rails new learn-capybara

Or you can create a new project using rails-composer.

rails new learn-capybara -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb -T -O

2. Rspec installation

========================= Now Install Rspec

rails generate rspec:install

3. Setup capybara

=====================

Gemfile :

Add this in your Gemfile.

group :test, :development do
  gem "rspec-rails"
end

group :test do
  gem "capybara"
end

Ok, now run bundle.

spec/spec_helper.rb configuration

Require capybara:

require 'capybara/rspec'

Capybara configration:

RSpec.configure do |config|
  config.include Capybara::DSL, :type => :request

4. Write your test

======================

5. Capybara-webkit

======================

Installation

Set Gemfile and spec_helper.rb

Gemfile

Add capybara-webkit and database-cleaner, You didn't need capybara any more in your Gemfile

  gem "capybara-webkit", :group => :test
  gem 'database_cleaner', :group => :test

Note : Ensured that you installed libqt4-dev libqtwebkit-dev before bundle

sudo apt-get install libqt4-dev libqtwebkit-dev

spec/spec_helper.rb configuration

Now, set capybara-webkit config

capybara-webkit configration

Of course, it require 'capybara/rspec' and set Capybara.javascript_driver = :webkit in your spec_helper

  require 'capybara/rspec'
  require 'capybara-webkit'
  Capybara.javascript_driver = :webkit

DatabaseCleaner configuration

You need database_cleaner because database transactions aren’t compatible with rspec drivers besides Rack::Test

  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

Using webkit

Use :js => true .

describe "after clicking about link", :js => true do
	before :each do
	   click_link('about')
	end
	it "displays posts" do
		page.should have_selector("h3", text: "This is simple app to learn capybara.")
	end
end

6. Finally run Rspec

======================== Ok, finally run your test, you can use one of these commands to run rspec:

rspec

If you want run it in your terminal but with show all tests documentation you can use format documentation or with shortcut -fd

rspec spec --format documentation
rspec -fd

Or if you want save your test in html page you can use format html

rspec spec --format html --out results.html