This is a quick and dirty reference guide to the absolute basics of RSpec 3.
My experience has been that beginner programmers don’t get enough practice with testing, and that a lot of RSpec references don’t specify which version they’re using and aren’t necessarily updated to reflect the evolution of best practices (like the switch from should to expect).
The general pattern to follow is to have a describe statement that wraps around it statements which do the actual heavy lifting:
describe Order do
it "human-readable does-something description" do
# expect statement - your test! - goes here
end
end
Only one expectation per it statement!
You can also create a context to organize your tests according to the various situations you’re testing:
describe Order do
context "invalid user" do
it "does not add item to cart" do
# expect statement
end
it "redirects to user login" do
# expect statement
end
end
end
There are a variety of kinds of things you can test for, and some of them are easy to mix up with each other. Some built-in matchers for testing objects:
expect(something).to eq(something) # equivalence expect(something).to be(something) # identity expect(something).to be false # value is false expect(something).to be_falsey # value is "falsey"
When you want to test something other than an object, you can use a block:
expect{
# do something
}.to change {something}.by(1)
expect{
# do something
}.to raise_exception(ExceptionName)
There are quite a few resources out there that do an excellent job of contradicting each other, so try to get at least a couple different opinions on something (like before vs let) before you use it!
June 30, 2014 - posted by jessica