Ruby on Rails + Rspec + Capybara Initial Setup

Tadashi Shigeoka ·  Thu, August 31, 2017

I’ll introduce the steps for setting up Rspec and Capybara in Ruby on Rails 5 and running test cases.

Ruby on Rails | ルビーオンレイルズ

Installing Gem rspec, rspec-rails

First, add the rspec and rspec-rails gems to your Gemfile and run bundle install.

Gemfile

group :development, :test do
  ## Rspec ##
  # Rspec main library
  gem 'rspec'
  # Rspec library for Rails
  gem 'rspec-rails'
end
bundle install

Rspec Initial Setup

Next, run the rails generate rspec:install command to perform the initial setup for Rspec.

bundle exec rails generate rspec:install
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb

After running the command, the following files for configuration are created:

  • .rspec
  • spec/spec_helper.rb
  • spec/rails_helper.rb

Running Feature Tests with Capybara

Finally, let’s run Rails Feature tests with Capybara.

The content of the Feature test case below is simple: when accessing the top page, it should return HTTP Status code 200.

spec/features/homes_spec.rb

require 'rails_helper'

RSpec.feature "Home page", type: :feature do
  scenario "access to index" do
    visit "/"
    expect(page.status_code).to eq(200)
  end
end

When I executed the added test, I confirmed that the test passed successfully.

bundle exec rspec                           
.

Finished in 2.62 seconds (files took 2.99 seconds to load)
1 example, 0 failures

With this, I confirmed that simple E2E tests using Capybara are working.

That’s all from the Gemba, where I want to write test code with Rails + Rspec + Capybara.