An introduction to using Capybara with RSpec to test web pages in a Rails app.

This episode covers:

  • Configuring Capybara with RSpec
  • Visiting pages
  • Expecting content to be present
  • Clicking links
  • Testing the current URL

If you’re interested in learning more about Capybara, the project’s README is great. I’ll also be covering it more in future episodes.

View the code.

View the diff.

View the playlist.

Key code from the episode:

spec/rails_helper.rb:

# Add this line below require 'rspec/rails'
require 'capybara/rspec'

spec/features/home_spec.rb:

require 'rails_helper'

RSpec.describe 'Home features' do
  it 'displays the name of the app and links to the About page' do
    visit('/home')
    expect(page).to have_content('Game Tracker')
    click_link('About')
    expect(current_path).to eql('/about')
    expect(page).to have_content('About')
  end
end

config/routes.rb:

Rails.application.routes.draw do
  get('home' => 'home#index')
  get('about' => 'about#index')
  get('status' => 'status#index')
  get('consoles' => 'consoles#index')
end

app/controllers/home_controller.rb:

class HomeController < ApplicationController
  def index
  end
end

app/views/home/index.html.erb:

<h1>Game Tracker</h1>

<%= link_to('About', about_path) %>

app/controllers/about_controller.rb:

class AboutController < ApplicationController
  def index
  end
end

app/views/about/index.html.erb:

<h1>About</h1>

Software used:

  • Ruby 2.4.2
  • RSpec 3.6.1
  • Capybara 2.15.4
  • Rails 5.1.4
  • Mac OS
  • iTerm 2
  • Vim
  • Tmux