The real problem here is that you're testing two things. You're testing that
the named_scope returns paid items, and that you can sum the cost of each of
those items.
If your total_cost method continues to use the named scope, then you won't be
able to get away from using the database, without stubbing out the named_scope
itself, which would be stubbing the object under test.
On 26/08/2011, at 12:09 PM, Scott Harvey wrote:
> Over the years I've gotten into the habit of saving all the associated
> objects I need in order to test a specific method.
>
> This means I would end up with a situation something like this:
>
> 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
>
> In an effort to get my tests running quicker I would like to be able to test
> this type of situation without saving to the database.
>
> I've heard it said that you should never stub the object under test but
> instead mock and stub associated objects as needed. I'm just not sure how to
> go about stubbing the LineItem class in this case without rendering the test
> useless.
>
> Anyone have any thoughts on how this could be done or any more general tips
> on speeding up Rails tests?
>
> Scott
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby or Rails Oceania" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/rails-oceania/-/Do3fM2YDVc0J.
> 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.
--
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.