Skip to content

Instantly share code, notes, and snippets.

@jsuchal
Last active August 29, 2015 14:04
Show Gist options
  • Save jsuchal/cbaf3052eac84abaa347 to your computer and use it in GitHub Desktop.
Save jsuchal/cbaf3052eac84abaa347 to your computer and use it in GitHub Desktop.
require 'rspec'
class CachedRepository
def initialize(repository)
@repository = repository
@cache = {}
end
def find(id)
unless @cache.include?(id)
@cache[id] = @repository.find(id)
end
@cache[id]
end
end
describe CachedRepository do
it 'calls find only once' do
repository = double
expect(repository).to receive(:find).once
cr = CachedRepository.new(repository)
cr.find(5)
cr.find(5)
end
it 'returns same value when called twice' do
repository = double(find: :value)
cr = CachedRepository.new(repository)
expect(cr.find(5)).to eq(:value)
expect(cr.find(5)).to eq(:value)
end
it 'returns different value when called with different args' do
repository = double
expect(repository).to receive(:find).with(5).and_return(:value)
expect(repository).to receive(:find).with(6).and_return(:another_value)
cr = CachedRepository.new(repository)
expect(cr.find(5)).to eq(:value)
expect(cr.find(6)).to eq(:another_value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment