RSpec GetStarted

RSpec

RSpec is testing tool for the Ruby programming language.
This is useful for Rails.

Contents


Create application without test

When creating project, with –skip–test-unit

rails new new_app --skip--test-unit

Not create Test directory Not use Test:Unit


Package

Edit GemFile

gourp :development, :test do
   gem 'rspec-rails', '~> 3.1.0'
   #gem 'spring-commands-rspec', '~> 1.0.1'
   gem 'capybara', '~> 2.4.3'
   gem 'factory_girl_rails', '~> 4.4.1'
   gem 'database_cleaner', '~> 1.3.0'
end

Any version is fine.
Please refer rspec | RubyGems.org etc… to check version

Next, you need to update

bundle install --without production
bundle update
bundle install

Maybe, only bundle is fine

bundle

Package Details

  • rspec-rails
  • : RSpec Core

  • spring-commands-rspec
  • : RSpec spring

  • capybara
  • : simulator of Browser

  • factory_girl
  • : Add Test data to database


Install rspec

Change rails setting to use rspec instead of Test::Unit

rails g rspec:install

Create rspec files under spec/

“spec” directory : RSpec Test root directory
spec/models: Model
spec/requests: API


Sample Tests

Simple

Web

require 'spec_helper'
describe "Static pages" do

  describe "Home page" do

    it "Content has 'Sample App'(Comment)" do
      visit '/static_pages/home'   # capybara visit
      expect(page).to have_content('Sample App')
      expect(page).to have_title("Ruby on Rails Title");
    end
  end
end

Run Tests

How to run test

Use rspec command and file name

rspec spec/requests/static_pages_spec.rb

Run test on the line

rspec file.rb --line-number 10
rspec file.rb --line-number 10

How to run all test

rspec spec/

Use Tag

Add tag to test

example '', :testtag
end

:testtag is tag

rspec spec --tag=testtag