On 9 Oct 2008, at 18:20, Hongli Lai wrote:
I currently have a base class and 2 subclasses. I'm struggling with
finding the best way to test them. This is the current situation.
What's the best way to solve this? What are good practices for
testing inherited behavior? Should I be testing my child classes for
parent class behavior at all? Right now I'm doing it anyway in order
to detect bugs that I might have missed otherwise.
I've been meaning to blog about this, as I recently had an epiphany
about how brilliantly rspec handles this, IMO.
I actually do it pretty much the way you're doing it, but I don't
think it's ugly at all.
To me, the abstract superclass is just an implementation detail of the
concrete subclass - I don't need to or want to care that
implementation detail when I'm writing specifications about how the
concrete class should behave. Therefore while the behaviour which is
common between it and other classes that have the same superclass does
tend to end up in shared example groups, that's just because I'm
keeping my code nicely factored - the same specs would still be valid
if I copied and pasted the superclass code out into the two subclasses
and collapsed the hierarchy, or moved them into modules, or whatever.
It's a subtle shift, but if you try to let go of the implementation,
and think about the *behaviour* when you name your example groups,
you'll find they start to read more naturally.
In your case, the two concrete servers can just say
it_should_behave_like "a server"
and pull in the specifications for the behaviour that is common to both.
At songkick, for example, we're modelling bands playing gigs. We have
an abstract Event superclass, subclassed by Concert and Festival. The
spec for Event reads like this:
describe Event do
it "should be abstract"
lambda { Event.new }.should raise_error(TypeError)
end
end
Then the two subclasses mix in a module containing the shared example
groups, and at the top, they say
describe Concert do
extend SK::Spec::Models::ExampleGroups #shared example groups for
models live in here
it_should_behave_like "an event"
# special concert behaviour spec'd here...
I've tried to find a pattern I was comfortable with for this with
xUnit tests, and never managed it. For me, rspec's solution fits the
problem like a glove.
HTH,
Matt
_______________________________________________
rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users