Need to reload current_cart to get the test passed

Posted by leomayleomay on Stack Overflow See other posts from Stack Overflow or by leomayleomay
Published on 2011-03-14T08:06:53Z Indexed on 2011/03/14 8:10 UTC
Read the original article Hit count: 247

Filed under:
|

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 '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

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about rspec