Switch branches/tags
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
148 lines (108 sloc) 3.34 KB

RSpec Expectations

RSpec::Expectations lets you express expected outcomes on an object in an example.

account.balance.should eq(, :USD))


If you want to use rspec-expectations with rspec, just install the rspec gem and RubyGems will also install rspec-expectations for you (along with rspec-core and rspec-mocks):

gem install rspec

If you want to use rspec-expectations with another tool, like Test::Unit, Minitest, or Cucumber, you can install it directly:

gem install rspec-expectations

Basic usage

Here's an example using rspec-core:

describe Order do
  it "sums the prices of the items in its line items" do
    order =
    order.add_entry( =>
      :price =>, :USD)
    order.add_entry( =>
      :price =>, :USD),
      :quantity => 2
    ))) eq(, :USD))

The describe and it methods come from rspec-core. The Order, LineItem, and Item classes would be from your code. The last line of the example expresses an expected outcome. If ==, :USD), then the example passes. If not, it fails with a message like:

expected: #<Money @value=5.55 @currency=:USD>
     got: #<Money @value=1.11 @currency=:USD>

Built-in matchers


actual.should eq(expected)  # passes if actual == expected
actual.should == expected   # passes if actual == expected
actual.should eql(expected) # passes if actual.eql?(expected)


actual.should be(expected)    # passes if actual.equal?(expected)
actual.should equal(expected) # passes if actual.equal?(expected)


actual.should be >  expected
actual.should be >= expected
actual.should be <= expected
actual.should be <  expected
actual.should be_within(delta).of(expected)

Regular expressions

actual.should =~ /expression/
actual.should match(/expression/)


actual.should be_an_instance_of(expected)
actual.should be_a_kind_of(expected)


actual.should be_true  # passes if actual is truthy (not nil or false)
actual.should be_false # passes if actual is falsy (nil or false)
actual.should be_nil   # passes if actual is nil

Expecting errors

expect { ... }.to raise_error
expect { ... }.to raise_error(ErrorClass)
expect { ... }.to raise_error("message")
expect { ... }.to raise_error(ErrorClass, "message")

Expecting throws

expect { ... }.to throw_symbol
expect { ... }.to throw_symbol(:symbol)
expect { ... }.to throw_symbol(:symbol, 'value')

Predicate matchers

actual.should be_xxx         # passes if
actual.should have_xxx(:arg) # passes if actual.has_xxx?(:arg)

Ranges (Ruby >= 1.9 only)

(1..10).should cover(3)

Collection membership

actual.should include(expected)


[1,2,3].should include(1)
[1,2,3].should include(1, 2)
{:a => 'b'}.should include(:a => 'b')
"this string".should include("is str")

Also see