Skip to content

Instantly share code, notes, and snippets.

@benhamill
Created February 9, 2011 03:46
Show Gist options
  • Save benhamill/817848 to your computer and use it in GitHub Desktop.
Save benhamill/817848 to your computer and use it in GitHub Desktop.
require 'yaml'
module MyModule
module ClassMethods
def from_yaml(file=nil)
# ...
end
end
module InstanceMethods
def to_yaml(file=nil)
file ||= "tmp/#{name.downcase}.yaml"
File.open(file, 'w') do |file|
f.puts YAML.dump(to_hash)
end
end
def to_hash
# ...
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
require 'my_module'
class MyModuleHolder
include MyModule
end
describe "MyModule" do
# ...
context "instance methods" do
subject { MyModuleHolder.new }
# ...
describe "to_yaml" do
before(:each) do
@directory = "tmp/specs"
@file_location = "#{@directory}/test.yaml"
Dir.mkdir(@directory) unless Dir.exists?(@directory)
File.delete(@file_location) if File.exists?(@file_location)
end
after(:each) do
File.delete(@file_location) if File.exists?(@file_location)
end
it "should write to a given file" do
subject.should_receive(:to_hash) { { 'foo' => 'bar', 'baz' => 'bom' } }
subject.to_yaml(@file_location)
File.exists?(@file_location).should == true
end
it "should convert the object's hash to yaml" do
subject.should_receive(:to_hash) { { 'foo' => 'bar', 'baz' => 'bom' } }
subject.to_yaml(@file_location)
expected_yaml = <<-YAML
---
foo: bar
baz: bom
YAML
File.read(@file_location).should == expected_yaml
end
end
end
end
@benhamill
Copy link
Author

Why do these specs fail with "undefined local variable or method 'to_hash' for #MyModuleHolder:0xhexstuff"?

@timtyrrell
Copy link

cut and paste fail? "indlue MyModule"

@benhamill
Copy link
Author

Retyping fail. Good eye. Fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment