Created
August 18, 2014 19:37
-
-
Save saxxi/72ebe2929c8758f33a11 to your computer and use it in GitHub Desktop.
Ruby Rspec - Testable classes with dependencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rspec' | |
require 'date' | |
class Person | |
def can_drink? | |
age >= 21 | |
end | |
def age | |
date_class.today.year - 1975 | |
end | |
def date_class | |
Date | |
end | |
end | |
describe "Testable classes with dependencies" do | |
let(:user){ Person.new } | |
let(:fakeDate){ double "Date", today: Date.new(1995) } | |
it "Default behaviour" do | |
expect(user.can_drink?).to eq true | |
end | |
it "Method stubbing" do | |
# Hook into the date class | |
allow(Date).to receive(:today).and_return Date.new(1995) | |
expect(user.can_drink?).to eq false | |
end | |
it "Dependency injection" do | |
# Create a fake Date class and stub only the date_class inside Person. | |
# On complex scenarios this is usually a better choice. | |
allow(user).to receive(:date_class).and_return fakeDate | |
expect(user.can_drink?).to eq false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment