RSpec
rspec path/to/my_spec.rb:line
RSpec.describe Constant do
context '#method' do
it 'returns 1' do
result = Constant.method
expect(result).to eq(1)
end
end
end
Terminology
Because [RSpec] uses a DSL to write tests, there's a layer of separation between the keywords you use and the internal terms for what's instantiated. Here's the mapping:
describe- an ExampleGroupit- an Exampleexpect()- an ExpectationTargetto()- a Matcherlet()- creates a memoized helper method
Sources
Expectations
RSpec has at least four ways to define expectations. As of 2012, the recommended syntax is expect() and it { is_expected.to }. They are more reliable than the older should and it { should } syntaxes. For more details, see this post.
Expect
expect() syntax lets you define an expectation on an explicit object.
expect(actual).to eq(expected)
expect(actual).to be > expected
expect([1, 2, 3]).to_not include(4)
It Is Expected To
it { is_expected.to } syntax lets you define an expectation on a previously-defined subject.
subject { Person.new(:birthdate => 19.years.ago) }
it { is_expected.to be_eligible_to_vote }
Should (Deprecated)
should syntax lets you define an expectation on an explicit object.
actual.should eq expected
actual.should be > 3
[1, 2, 3].should_not include 4
It Should (Deprecated)
it { should } syntax lets you define an expectation on a previously-defined subject.
subject { Person.new(:birthdate => 19.years.ago) }
it { should be_eligible_to_vote }
RSpec-Rails
The types of test that RSpec-Rails makes available.
- Feature: An acceptance test, simulating a browser session. Uses Capybara. Generated with
rails generate integration_test. In Rails, integration tests can test for page elements, but can't interact with links or forms. - Request: Simulates one or more HTTP requests. Equivalent to a Rails integration test. Andy Lindeman recommends this for web service testing.
- Controller: Calls a controller method directly. Doesn't render a view, but allows you to test what view would be rendered and what data is passed to it. Equivalent to a Rails functional/controller test. In Rails, controller tests do render views.
- Routing: Tests mapping of requested paths to controllers.
- Model: Tests a model, including hitting the database.
- View: Tests a view template in isolation.
- Helper: Tests helper methods.
Misc Features
contain_exactlya_hash_includingit '…', :aggregate failures do- run all expectations and show all failing ones
Slapdash