This is a cheat sheet for RSpec, including its methods, and test doubles. It also includes FactoryGirl methods, even though that is separate from RSpec. This cheat sheet is based on Rails 4 Test Prescriptions by Noel Rappin (the best of a bad lot when it comes to RSpec books) and the RSpec documentation published on Relish. RSpec documentation is generally not very good, which is why I created this cheat sheet for myself.
Standard stub (to intercept a method call), for objects and classes, respectively:
allow(object).to receive(:method)[.and_return(value)]
allow(Class).to receive(:method)[.and_return(value)]
For instance method, where the object cannot be easily ascertained (eg, checking value after a DB transaction):
allow_any_instance_of(Class).to receive(:method)[.and_return(value)]
To intercept a 'nested' method call on an object (eg, printing errors from an
ActiveRecord
method call on an object):
allow(object).to receive_message_chain("method1.method2")[.and_return(value)]
To use these as expectations (using #expect
) the expectation must go before
the test code that should trigger methods satisfying the expectation (just like
using allow
but in contrast the usual place of expectations, which is at the
end of the example).
Full listing of built-in matchers.
To create an object in the DB:
obj = create(:class)
To create an object without saving to the DB. You can call #save
on the object
later.
obj = build(:class)
If :class
contains associations, then FactoryGirl will also create those
objects, but with #create
unless a different strategy is specified
using the :strategy
parameter to #association
. Q: What is a [build]
strategy?
To create an object that is not saved in the DB, but will have a fake ActiveRecord ID anyway:
obj = build_stubbed(:class)
This will create associations using #build_stubbed
, not #create
.
#build_stubbed
raises an exception if any of the ActiveRecord methods (eg,
#save
) are called on the object.
An object used as a stand-in for another object. #double
is provided by
RSpec.
The basic form simply creates a dummy object with an optional list of methods it responds to, and their return values. It returns an error if a method not specified is called on the object. Q: Does "error" mean "raise an exception"?
obj = double("Object Name", [method: return_val]*)
Verifying doubles are based on actual objects, and returns an error if a method that does not exist on the actual object is called. The following methods are for instance and class doubles, respectively. Q: Does "error" mean "raise an exception"?
obj = instance_double(:class, [method: return_val]*)
obj = class_double(Class, [method: return_val]*)
Maybe I'll never fill this in.
Sandi Metz wouldn't fill in "Controller Specs" ;)