class Order < AR
has_many :line_items
def total_cost
line_items.paid.sum(&:cost)
end
end
class LineItem < AR
belongs_to :order
named_scope :paid, :conditions => { :paid => true }
end
it 'total_cost returns the total of all the line items' do
order = Order.create
order.line_items.create!(:cost => 10, :paid => true)
order.line_items.create!(:cost => 20, :paid => true)
order.line_items.create!(:cost => 50, :paid => false)
order.total_cost.should == 30
end
On 26/08/2011, at 2:09 PM, Scott Harvey wrote:
> The paid named_scope in the example is on the LineItem model so stubbing that
> out would not be stubbing out the object under test.
I clearly need more coffee! (or is it less coffee?)
> The test that checks that the paid named_scope works will be in the LineItem
> spec folder so I'm happy to stub the named_scope out if there is a nice way
> to do that.
In that case, something like this would completely avoid the database: (I
haven't checked the syntax at all)
it 'total_cost returns the total of all the line items' do
order = Order.new
line_items = [stub(:cost => 10), stub(:cost => 20)]
order.stub(:line_items).and_return(stub(:paid => line_items))
order.total_cost.should == 30
end
You only need to stub the bits you're using, hence no paid methods on the
line_item stubs. You also don't need to save the order object, you can just use
the in memory representation.
--
You received this message because you are subscribed to the Google Groups "Ruby
or Rails Oceania" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rails-oceania?hl=en.