Skip to content

Instantly share code, notes, and snippets.

@modsognir
Forked from notahat/valid.rb
Created October 11, 2012 02:54
Show Gist options
  • Save modsognir/3869892 to your computer and use it in GitHub Desktop.
Save modsognir/3869892 to your computer and use it in GitHub Desktop.
Testing fail?
# I have a class that delegates functionality to a couple of objects that it
# constructs. I want to test this in isolation. I want to make sure that the
# objects are constructed with the right arguments. I also want to make sure
# that the results from the objects are handled correctly.
#
# I'm finding it hard to structure the code and test in a way that isn't
# cumbersome. What's below works, but it feels like a lot of stubbing and setup
# for something the should be simpler.
#
# Anyone got a better approach for this?
class TopLevelValidator
def initialize(some_info)
@some_info = some_info
end
def valid?
validator_a = validator_a_class.new(@some_info)
validator_b = validator_b_class.new(@some_info)
validator_a.valid? && validator_b.valid?
end
private
def validator_a_class
ValidatorA
end
def validator_b_class
ValidatorB
end
end
describe TopLevelValidator do
let(:some_info) { stub }
let(:passing_validator) { stub(:valid? => true) }
let(:failing_validator) { stub(:valid? => false) }
let(:validator_a_class) { stub(:new => passing_validator) }
let(:validator_b_class) { stub(:new => passing_validator) }
subject do
described_class.new(some_info).tap do |validator|
validator.stub(
:validator_a_class => validator_a_class,
:validator_b_class => validator_b_class
)
end
end
it "passes the right info to validator A" do
validator_a_class.should_receive(:new).with(some_info)
subject.valid?
end
it "is invalid if validator A says so" do
validator_a_class.stub(:new => failing_validator)
subject.should_not be_valid
end
it "passes the right info to validator B" do
validator_b_class.should_receive(:new).with(some_info)
subject.valid?
end
it "is invalid if validator B says so" do
validator_b_class.stub(:new => failing_validator)
subject.should_not be_valid
end
it "is valid if both validators say so" do
subject.should be_valid
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment