【问题标题】:Testing a class method for a model using Rspec and FactoryGirl in Rails在 Rails 中使用 Rspec 和 FactoryGirl 测试模型的类方法
【发布时间】:2013-08-06 10:01:22
【问题描述】:

我是 Rspec 和 FactoryGirl 测试 ROR 应用程序的新手。我正在尝试测试模型类方法add_product(product_id),尽管当我在浏览器上尝试相同方法时它仍然有效,但它一直失败。这是模型的代码:

class Cart < ActiveRecord::Base
  has_many :line_items, inverse_of: :cart

  def add_product(product_id)
    current_item = line_items.find_by_product_id(product_id)
    if current_item
      current_item.quantity += 1
    else
      current_item = line_items.build(:product_id => product_id)
    end
    current_item
  end
end

这是购物车模型的失败规范:

describe Cart do
  before(:each) do
    @cart = FactoryGirl.create(:cart)
    @product = FactoryGirl.create(:product)
    @line_item = FactoryGirl.create(:line_item, product_id: @product.id, cart_id: @cart.id)
  end
  it 'increases the quantity of line_item when a similar product is added' do
    lambda {@cart.add_product(@product.id)}.should change {@line_item.quantity}.by(1)
  end
end

这失败了,我从 Rspec Failure/Error: lambda {@cart.add_product(@product.id)}.should change {@line_item.quantity}.by(1) result should have been changed by 1, but was changed by 0 收到这条消息

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec shopping-cart rspec-rails


    【解决方案1】:

    数量正在更新,但您永远不会保留数据。所以数据永远不会进入数据库,测试也永远不会看到变化。您将遇到与 .build 相同的问题,除非您明确表示,否则它不会持久存在。你可以通过这样做来改变它。

    class Cart < ActiveRecord::Base
      has_many :line_items, inverse_of: :cart
    
      def add_product(product_id)
        current_item = line_items.find_by_product_id(product_id)
        if current_item
          current_item.quantity += 1
          current_item.save
        else
          current_item = line_items.create(:product_id => product_id)
        end
        current_item
      end
    end
    

    【讨论】:

    • 感谢@Eric 的快速响应,但在坚持current_item 后测试仍然失败,是否有另一种方法可以重新编写规范以执行相同的测试?
    • 当然可以@cart.add_product(@product.id).quantity.should eq 2 这种方法的问题是它不会测试您的项目是否以这种方式持续存在。它只是测试你的逻辑是否有效。
    • 我只是想测试逻辑,我将项目保留在我的代码的不同部分,我将测试它是如何保留在该部分的。你的答案就是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多