Skip to content

Instantly share code, notes, and snippets.

@notahat
Created October 11, 2012 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save notahat/3869884 to your computer and use it in GitHub Desktop.
Save notahat/3869884 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 valid?(info, more_info, even_more_info)
validator_a.valid?(info, more_info) &&
validator_b.valid?(info, even_more_info)
end
private
def validator_a
ValidatorA.new
end
def validator_b
ValidatorB.new
end
end
describe TopLevelValidator do
let(:info) { stub }
let(:more_info) { stub }
let(:even_more_info) { stub }
let(:validator_a) { stub(:valid? => true) }
let(:validator_b) { stub(:valid? => true) }
before do
subject.stub(
:validator_a => validator_a,
:validator_b => validator_b
)
end
it "passes the right info to validator A" do
validator_a.should_receive(:valid?).with(info, more_info)
subject.valid?(info, more_info, even_more_info)
end
it "is invalid if validator A says so" do
validator_a.stub(:valid? => false)
subject.valid?(info, more_info, even_more_info).should be_false
end
it "passes the right info to validator B" do
validator_b.should_receive(:valid?).with(info, even_more_info)
subject.valid?(info, more_info, even_more_info)
end
it "is invalid if validator B says so" do
validator_b.stub(:valid? => false)
subject.valid?(info, more_info, even_more_info).should be_false
end
it "is valid if both validators say so" do
subject.valid?(info, more_info, even_more_info).should be_true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment