RSpec Matchers

Hey! Click on underlined code for more options.
expect
{
engine.start
}
.to
change
{ engine.state }.
from
(:off).
to
(:on)
(engine, :state).
from
(:off).
to
(:on)
expect
{
User.create name: ‘John’
}
.to
change
{ User.count }.
by
1
(User, :count).
by
1
expect
{
post.save
}
.to
change
{ post.updated_at }(post, :updated_at)
expect
{ raise "what the hell!" }
.to
raise_error
raise_exception
raising
RuntimeError, "what the hell!"/hell/"what the hell!"RuntimeError
Be aware of using raise_error without params, since it catch ANY errors, including syntax errors

dynamic predicate matchers

obj.
smth
?
->   
be_
smth
obj.
has_
smth
?
->
have_
smth
prefix the method with
be_
and remove the question mark
Some examples:
  • expect
    (num)
    .to    
    be_even
    be_between
    1, 10
    be_integer
    be_real
  • expect
    (hash)
    .to   
    have_key
    :foo
    be_empty
  • expect
    (post)
    .to   
    be_published
    be_trending
  • expect
    (obj)
    .to    
    be_kind_of
    Numeric
    be_instance_of
    Fixnum
  • expect
    (record)
    .to
    be_valid
    be_persisted
    be_new_record
Also almost all machers
expect
(a)
.to
eq
(b)
alias:
be
== b

dealing with floats

expect
(Math::PI)
.to
  • be_within
    (0.01).
    of
    (3.14)

numbers

expect
(a)
.to
  • be
    > b
  • be
    < b
  • be
    >= b
  • be
    <= b

booleans

expect
(obj)
.to
  • be
    (if not nil or false)
  • be
    true
  • be_nil
  • be_falsey
    (nil or false)
  • be_truthy
    (not nil or false)

arrays

expect
([1, 2, 3])
.to
  • include
    2, 3
  • match_array
    [2, 3, 1]
  • contain_exactly
    2, 3, 1

strings

expect
("hello")
.to
  • include
    "ll"
  • start_with
    "hell"
  • end_with
    "lo"
  • match
    /^[a-z]+$/

hashes

expect
(a: 1, c: 3)
.to
  • include
    c: 3:c

dealing with UI

expect
(person)
.to
have_attributes
name: "John", email: "john@gmail.com"
expect
(9)
.to
satisfy
{ |x| x % 3 == 0 }
expect
(post)
.to
respond_to
(:update).
with
(1).
argument