Question

This may be a naive question, but does RSpec's testing DSL violate the law of Demeter?

Here's an example of the RSpec DSL from http://rspec.info:

bowling.score.should eq(0)

From a Demeter perspective, this seems to me indistinguishable from this example:

user.department.try(:name)

which according to Avdi Grimm is a violation of the Law of Demeter.

Source: http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/

Was it helpful?

Solution

This is obviously subjective, but I believe it does not.

The should call is part of the language of RSpec, which just happens to be built upon Ruby. There's no reason it couldn't be:

should_be_equal(bowling.score, 0)

(or similar) but that's not the language of RSpec. Further, the should method only exists on that object within specs, for the specs.

To try and (somewhat crudely, perhaps) better illustrate my argument about being a part of the language:

bowling.score + 10

is actually calling the + method on score, but would you see this as a law of demeter violation? The + is seen as an operator rather than a method, much like should be above.

OTHER TIPS

Demeter is a risk-reduction guideline motivated by the idea that the less one part of the system depends on the structure of other parts, the less likely that part will be impacted by changes to said structure.

You could certainly argue that game.score.should eq(0) is a Demeter violation, but the should method is part of the rspec framework, which is the context around the statement game.score.should eq(0) and is not likely to change in a way that would force changes to this statement.

Maybe it violates Demeter, maybe it doesn't, but the risk that Demeter aims to address is not really present.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top