需要重新加载current_cart才能通过测试

时间:2011-03-14 08:06:53

标签: ruby-on-rails rspec

我正在使用RSpec测试我的在线商店应用程序,这就是我正在做的事情:

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

describe LineItemsController do

  describe "POST 'create'" 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

现在的问题是它从来没有将两个具有相同产品的line_items合二为一,因为我第二次进入line_items_controller#createcurrent_cart.line_items是[],我已经运行{{ 1}}让测试通过,任何想法出了什么问题?

1 个答案:

答案 0 :(得分:0)

可能是因为你已经删除了控制器的current_cart,它总是返回没有line_items的Factory(:cart)

如果您正在测试current_cart本身,也许最好不要将其删除。

此外,@line_item.save调用是否返回true?