Professional Documents
Culture Documents
Basic Matchers
> eq
> include
describe Array do
it 'has two things' do
expect(%w(thing1 thing2).length).to eq 2
end
end
it "works with strings" do
> match
match asserts with a regular expression match.
describe User
User, '.build_with_default_ssn' do
it 'generates a valid SSN' do
user_with_default_ssn = User
User.build_with_default_ssn
> be_true
be_true asserts truthiness.
describe User
User, '#admin?' do
it 'returns true when privileges include :admin' do
user = User
User.new(privileges: [:admin])
expect(user.admin?).to be_true
end
end
> be_false
be_false asserts falsiness.
describe User
User, '#admin?' do
it 'returns false when privileges are empty' do
user = User
User.new(privileges: [])
expect(user.admin?).to be_false
end
end
1 of 2
Exceptions
Predicates
> raise_error
RSpec is kind enough to match predicate methods (methods ending with a ?) with
appropriate matchers which read easily.
In exceptional situations, youll want to raise in Ruby. Testing can be done with expect,
passing a block, and then calling raise_error. The class and error message are
optional.
describe SocialNetworkNotifier
SocialNetworkNotifier, 'when the network is down' do
it 'raises when contacting Twitter fails' do
fake_network_outage
describe 'predicates' do
it 'works with all Ruby objects' do
expect(nil).to be_nil
expect(%w(thing1 thing2)).not_to be_empty
end
end
expect {
SocialNetworkNotifier
SocialNetworkNotifier.notify_twitter_with(MessageBuilder
MessageBuilder.generate)
}.to raise_error(SocialNetworkNotifier
SocialNetworkNotifier::NetworkUnreachableError
NetworkUnreachableError,
expect(User
User.new(privileges: [:admin])).to be_admin
end
expect(User
User.new(privileges: [])).not_to be_admin
end
end
fake_network_outage
expect {
SocialNetworkNotifier
SocialNetworkNotifier.notify_facebook_with(MessageBuilder
MessageBuilder.generate)
}.to raise_error(SocialNetworkNotifier
SocialNetworkNotifier::NetworkUnreachableError
NetworkUnreachableError, /Facebook/)
end
end
2 of 2