Skip to content

Instantly share code, notes, and snippets.

@mdub
Forked from adzap/valid.rb
Created October 11, 2012 06:28
Show Gist options
  • Save mdub/3870584 to your computer and use it in GitHub Desktop.
Save mdub/3870584 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
class << self
attr_accessor :validator_classes
end
self.validator_classes = [ ValidatorA, ValidatorB ]
def initialize(some_info)
@validators = self.class.validator_classes.map { |v| v.new(some_info) }
end
def valid?
@validators.all? { |v| v.valid? }
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) }
before do
TopLevelValidator.stub(:validator_classes) { [ validator_a_class, validator_b_class ] }
end
subject do
described_class.new(some_info)
end
it "passes the right info to each validator" do
validator_a_class.should_receive(:new).with(some_info)
validator_b_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 "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 all validators say so" do
subject.should be_valid
end
end
@adzap
Copy link

adzap commented Oct 12, 2012

Much better idea with the stub.

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