-
-
Save adzap/3870377 to your computer and use it in GitHub Desktop.
Testing fail?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
@some_info = some_info | |
end | |
def valid? | |
validators.all? { |v| v.valid? } | |
end | |
def validators | |
self.class.validator_classes.map { |v| v.new(@some_info) } | |
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(:all) do | |
@original_validator_classes = TopLevelValidator.validator_classes | |
end | |
after(:all) do | |
TopLevelValidator.validator_classes = @original_validator_classes | |
end | |
before do | |
TopLevelValidator.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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment