开发者

Need to reload current_cart to get the test passed

I'm testing my online store app with RSpec, here's what I'm doing:

# spec/controllers/line_items_controller_spec.rb
require 'spec_helper'

describe LineItemsController do

  describe "POST '开发者_如何学JAVAcreate'" do
    before do
      @current_cart = Factory(:cart)
      controller.stub!(:current_cart).and_return(@current_cart)
    end

    it 'should merge two same line_items into one' do
      @product = Factory(:product, :name => "Tee")
      post 'create', {:product_id => @product.id}
      post 'create', {:product_id => @product.id}

      assert LineItem.count.should == 1
      assert LineItem.first.quantity.should == 2
    end
  end    
end

# app/controllers/line_items_controller.rb
class LineItemsController < ApplicationController
  def create        
    current_cart.line_items.each do |line_item|
      if line_item.product_id == params[:product_id]
        line_item.quantity += 1
        if line_item.save
          render :text => "success"
        else
          render :text => "failed"
        end
        return
      end
    end

    @line_item = current_cart.line_items.new(:product_id => params[:product_id])

    if @line_item.save
      render :text => "success"
    else
      render :text => "failed"
    end
  end
end

The problem right now is it never added up two line_items having the same product into one, because the second time I entered into the line_items_controller#create, the current_cart.line_items is [], I have run current_cart.reload to get the test passed, any idea what's going wrong?


It's possible that because you have stubbed out the controller's current_cart it's always returning Factory(:cart) which has no line_items.

If you're testing current_cart itself maybe it's best not to stub it out.

Also, is the @line_item.save call returning true?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜