Skip to content

Instantly share code, notes, and snippets.

@joshuaclayton
Forked from kornypoet/gist:1689638
Created January 27, 2012 16:38
Show Gist options
  • Save joshuaclayton/1689665 to your computer and use it in GitHub Desktop.
Save joshuaclayton/1689665 to your computer and use it in GitHub Desktop.
Rspec #initialize behavior
class Foo
attr_accessor :bar
def initialize(bar, validator = BarValidator)
validator.validate!(bar)
@bar = bar
end
end
class BarValidator
class MissingKey < ArgumentError; end
def self.validate!(bar)
if !bar.has_key?(:awesome)
raise MissingKey, "object is missing key :awesome"
end
end
end
describe Foo do
let(:bar) { stub("something awesome") }
context "when bar is valid" do
it "assigns bar correctly" do
validator = stub("valid validator", :validate! => true)
Foo.new(bar, validator).bar.should == bar
end
end
context "when bar is invalid" do
it "does not instantiate an object" do
validator = stub("valid validator")
validator.stub(:validate!).and_raise(ArgumentError.new("Something broke"))
expect { Foo.new(bar, validator) }.to raise_error(ArgumentError, "Something broke")
end
end
end
describe BarValidator do
it "does not raise if bar has a key of :awesome" do
expect { BarValidator.validate!(:awesome => "fuck yeah!") }.to_not raise_error
end
it "raises if bar is missing a key of :awesome" do
expect { BarValidator.validate!("awesome" => "oh noes!") }.to raise_error(BarValidator::MissingKey, "object is missing key :awesome")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment