Skip to content

Instantly share code, notes, and snippets.

@quamen
Forked from notahat/valid.rb
Created October 11, 2012 03:40
Show Gist options
  • Save quamen/3870009 to your computer and use it in GitHub Desktop.
Save quamen/3870009 to your computer and use it in GitHub Desktop.
Testing fail?
# ve 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 = ValidatorA.new(@some_info)
validator_b = ValidatorB.new(@some_info)
validator_a.valid? && validator_b.valid?
end
end
describe TopLevelValidator do
describe '#valid?' do
subject { described_class.new(some_info) }
let(:some_info) { 'foo' }
let(:validator_a) { stub('ValidatorA', :valid? => valid_a) }
let(:validator_b) { stub('ValidatorB', :valid? => valid_b) }
before do
stub_const("ValidatorA", Class.new).should_receive(:new).with(some_info) { validator_a }
stub_const("ValidatorB", Class.new).should_receive(:new).with(some_info) { validator_b }
end
context 'validator_a is valid' do
let(:valid_a) { true }
context 'validator_b is valid' do
let(:valid_b) { true }
it { should be_valid }
end
context 'validator_b is invalid' do
let(:valid_b) { false }
it { should_not be_valid }
end
end
context 'validator a and b are invalid' do
let(:valid_a) { false }
let(:valid_b) { false }
it { should_not be_valid }
end
end
end
@quamen
Copy link
Author

quamen commented Oct 11, 2012

Thanks for pointing that out. I've updated the gist to use stub_const.

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