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
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 methodSources
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()
syntax lets you define an expectation on an explicit object.
ruby
expect(actual).to eq(expected)
expect(actual).to be > expected
expect([1, 2, 3]).to_not include(4)
it { is_expected.to }
syntax lets you define an expectation on a previously-defined subject.
ruby
subject { Person.new(:birthdate => 19.years.ago) }
it { is_expected.to be_eligible_to_vote }
should
syntax lets you define an expectation on an explicit object.
ruby
actual.should eq expected
actual.should be > 3
[1, 2, 3].should_not include 4
it { should }
syntax lets you define an expectation on a previously-defined subject.
ruby
subject { Person.new(:birthdate => 19.years.ago) }
it { should be_eligible_to_vote }
The types of test that RSpec-Rails makes available.
rails generate integration_test
. In Rails, integration tests can test for page elements, but can’t interact with links or forms.contain_exactly
a_hash_including
it '…', :aggregate failures do
- run all expectations and show all failing ones