Skip to content

Instantly share code, notes, and snippets.

@jsheridanwells
Last active January 18, 2018 19:15
Show Gist options
  • Save jsheridanwells/8e8fe4ead13e57ba59dded8e5ee349f7 to your computer and use it in GitHub Desktop.
Save jsheridanwells/8e8fe4ead13e57ba59dded8e5ee349f7 to your computer and use it in GitHub Desktop.

RSpec TDD Tutorial

From this tutorial

  1. Set up new Rails app. -T flag skips installation of MiniTest:
$ rails new my_app -T
  1. Add RSpec to Gemfile.rb:
group :development, :test do
  gem 'rspec-rails'
end
  1. Bundle install: bundle

  2. Install RSpec files: rails g rspec:install

  3. When you generate a model, controller, etc., a spec will also be generated. Example:

$ rails g model User name:string email:string
  1. Set up the test and dev databases:
$ rails db: migrate
$ rails db:test:prepare
  1. To run all tests: $ bundle exec rspec or $ rake. To run one set: $ bundle exec spec/models. To run one set of tests: $ bundle exec spec/models/user_spec.rb. To run one tests: $ bundle exec spec/model/user_spec.rb:20

Testing Syntax

  1. describe : Scopes parts of the app to test, can take class name or string:
describe User do
 
end

As class grows, class name can be followed by a string to restrict scope to certain methods:

describe Agent, '#favorite_gadget' do
  ...
end
 
describe Agent, '#favorite_gun' do
  ...
end
 
describe Agent, '.gambler' do
  ...
end
  1. it blocks are the individual descriptions, testing units.
describe Agent, '#favorite_gadget' do
 
  it 'returns one item, the favorite gadget of the agent ' do
    ...
  end
 
end
  1. expect() Lets you verify or falsify parts of the system
describe Agent, '#favorite_gadget' do
 
  it 'returns one item, the favorite gadget of the agent ' do
    expect(agent.favorite_gadget).to eq 'Walther PPK'
  end
 
end
  1. Four phases of a test:
  • Setup . - Prepare the data
  • Exercise - Run the method you want to test
  • Verification . - Verify the assertion is met
  • Teardown . - (Usually handled by RSpec itself)

Matchers

  • .to eq()
  • .not_to eq()
  • .to be true
  • .to be_truthy
  • .to be false
  • .to be_falsy
  • .to be_nil
  • .not_to be_nil  * .to match() . : Useful for REGEX

Error matchers:

  • .to raise_error
  • .to raise_error(ErrorClass)
  • .to raise_error(ErrorClass, "Some error message")
  • .to raise_error("Some error message)

Callbacks

  • before(:each) do /../ end Runs a series of initializers or methods before running tests:
describe Agent, '#favorite_gadget' do
 
  before(:each) do
    @gagdet = Gadget.create(name: 'Walther PPK')
  end
 
  it 'returns one item, the favorite gadget of the agent ' do
    agent = Agent.create(name: 'James Bond')
    agent.favorite_gadgets << @gadget
 
    expect(agent.favorite_gadget).to eq 'Walther PPK'
  end
 
  ...
 
end
  • before(:all) . Runs once before all of the tests in a scope.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment