Skip to content

Instantly share code, notes, and snippets.

@saxxi
Created August 18, 2014 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxxi/72ebe2929c8758f33a11 to your computer and use it in GitHub Desktop.
Save saxxi/72ebe2929c8758f33a11 to your computer and use it in GitHub Desktop.
Ruby Rspec - Testable classes with dependencies
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