Skip to content

Instantly share code, notes, and snippets.

@allegrem
Created October 24, 2018 12:47
Show Gist options
  • Save allegrem/270eb9a82ffb816ff09c4048f0588705 to your computer and use it in GitHub Desktop.
Save allegrem/270eb9a82ffb816ff09c4048f0588705 to your computer and use it in GitHub Desktop.
# Double
book = double("book")
allow(book).to receive(:pages)
book.pages # => nil
expect(book).to have_received(:pages)
book.foo # exception
book = double("book")
expect(book).to receive(:pages) # will not raise an error if we call book.pages
book = double("book", pages: 250, author: "allegrem")
book.pages # => 250
book.foo # exception
# Verified Double
book = instance_double("Book", :pages => 250) # check methods exist, check args
# Partial test double
person = double("person")
allow(Person).to receive(:find) { person } # mock Person#find to return the double we have defined earlier
expect(Person).to receive(:find) { person } # same, but will fail if Person.find is not called
# Spy: same as a double, but allow all methods
book = spy('book')
book.pages
expect(book).to have_received(:pages)
# Configuring responses
book = double('book')
allow(book).to receive(:pages)
book.pages # => nil (by default)
allow(book).to receive(:pages).and_return(12)
allow(book).to receive(:pages) { 12 }
allow(book).to receive(:pages).and_return(1, 2, 3)
book.pages # => 1
book.pages # => 2
book.pages # => 3
allow(book).to receive(:pages).and_raise('Error') # or an exception class
allow(book).to receive(:pages).and_yield(1, 2, 3) # 1,2,3 will be passed as arguments to the block
# this will fail if pages is called without a block
allow(book).to receive(:pages).and_call_original
allow(book).to receive(:pages).and_wrap_original { |m, *args| m.call(*args).first(5) }
# Constraints
# see argument matching https://relishapp.com/rspec/rspec-mocks/v/3-8/docs/setting-constraints/matching-arguments
expect(book).to receive(:pages).once # all constraints are also available for have_received
expect(book).to receive(:pages).exactly(3).times
expect(book).to receive(:pages).at_least(3).times
expect(book).to receive(:pages).at_most(3).times
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment