[rspec-users] Depot app, Demeter's law and troubles cleanly specing

Lenny Marks lenny at aps.org
Sat Apr 18 18:08:06 EDT 2009

On Apr 18, 2009, at 1:17 PM, Fernando Perez wrote:

> Hi,
> Let's take the example of the depot app. In my controller I set  
> @order.
> Then in the view comes the bad stuff:
> @order.items.each do |item|
>  item.product.title
> end
> Now I'm having problems specing item.product.title. A quick and dirty
> fix is to trade a for for an underscore, so I create  
> Item#product_title:
> def product_title
>  product.title
> end
> The problem is that I have a few models that act the same way, so I
> would find myself writing lot's of these little instance methods, and
> the solution looks a bit stupid to me. So how do you handle such  
> issue?

Personally, I don't think its so bad to violate the 'Law of  
Demeter'(which of course is really just a guideline) in cases such as  
these dealing with domain models. All but the simplest apps will have  
entities that relate to other entities and each entity will of course  
have its own attributes. Sometimes I'll bring up a property from a  
child entity if its extremely common(as may be the case with  
product_title) but that's not the case most of the time. In this case,  
IF I was trying to spec a view for an 'Order', I'd probably use a  
factory method of some sort that would handle creating the desired  
object graph. If these models already exist, I usually use real  
objects in place of mocks. There are quite a few Factory/Builder type  
libs out there for ActiveRecord. In my case, we're typically dealing  
with Java/Hibernate domain layers through JRuby so I haven't used any  
of them, but its been simple enough to roll my own so far.

it "should show product title" do
     order = new_order(:title => 'the product title')



> I thought about composed_of, but AWDWR's examples still break  
> Demeter's
> law and that annoys me.

More information about the rspec-users mailing list