From this tutorial
- Set up new Rails app. -T flag skips installation of MiniTest:
$ rails new my_app -T
- Add RSpec to
Gemfile.rb
:
group :development, :test do
gem 'rspec-rails'
end
-
Bundle install:
bundle
-
Install RSpec files:
rails g rspec:install
-
When you generate a model, controller, etc., a spec will also be generated. Example:
$ rails g model User name:string email:string
- Set up the test and dev databases:
$ rails db: migrate
$ rails db:test:prepare
- 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
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
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
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
- 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)
.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)
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.