Skip to content

Commit

Permalink
Started implementing cassette cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
myronmarston committed Dec 3, 2011
1 parent 7304205 commit 70ca447
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/vcr/cassette/cache.rb
@@ -1,18 +1,28 @@
module VCR
class Cassette
class Cache
def initialize
@files = Hash.new do |files, file_name|
files[file_name] = File.exist?(file_name) ?
File.read(file_name) :
nil
end
end

def [](file_name)
File.read(file_name)
@files[file_name]
end

def exists_with_content?(file_name)
@files[file_name].to_s.size > 0
end

# TODO: test me
def []=(file_name, content)
directory = File.dirname(file_name)
FileUtils.mkdir_p directory unless File.exist?(directory)
File.open(file_name, 'w') { |f| f.write content }
end

def exists_with_content?(file_name)
File.size?(file_name)
@files[file_name] = content
end
end
end
Expand Down
69 changes: 69 additions & 0 deletions spec/vcr/cassette/cache_spec.rb
@@ -0,0 +1,69 @@
require 'vcr/cassette/cache'

module VCR
class Cassette
describe Cache do
describe "#[]" do
let(:content) { "the file content" }
let(:file_name) { "file.yml" }

it 'only reads the file once' do
File.stub(:exist?).with(file_name).and_return(true)
File.should_receive(:read).with(file_name).once.and_return(content)
subject[file_name].should eq(content)
subject[file_name].should eq(content)
subject[file_name].should eq(content)
end
end

describe "#exists_with_content?" do
context 'when the file exists with no content' do
let(:file_name) { "zero_bytes.yml" }

before(:each) do
File.stub(:exist?).with(file_name).and_return(true)
File.stub(:read).with(file_name).and_return("")
end

it 'returns false' do
subject.exists_with_content?(file_name).should be_false
end

it 'does not read the file multiple times' do
File.should_receive(:read).once
subject.exists_with_content?(file_name)
subject.exists_with_content?(file_name)
subject.exists_with_content?(file_name)
end

it "does not check for the file's existence multiple times" do
File.should_receive(:exist?).once
subject.exists_with_content?(file_name)
subject.exists_with_content?(file_name)
subject.exists_with_content?(file_name)
end
end

context 'when the file does not exist' do
let(:file_name) { "non_existant_file.yml" }

it 'returns false' do
subject.exists_with_content?(file_name).should be_false
end

it 'does not attempt to read the file' do
File.should_not_receive(:read)
subject.exists_with_content?(file_name)
end

it "does not check for the file's existence multiple times" do
File.should_receive(:exist?).once.with(file_name).and_return(false)
subject.exists_with_content?(file_name)
subject.exists_with_content?(file_name)
subject.exists_with_content?(file_name)
end
end
end
end
end
end

0 comments on commit 70ca447

Please sign in to comment.