给出以下代码:

class FooController < ApplicationController
  def create
    if auth_is_alright && params_are_cool #pseudocode
      @bar_results = BarService.new(param).run
    end
  end
end

class BarService
  def initialize(params)
    @transaction_token = params[:transaction_token]
    @id = params[:id]
    @quantity = params[:quantity]
    @value = params[:value]
    if Transaction.where(token: @transaction_token).any?
      _undo_previous_run
    end
  end

  def run
    Transaction.new(token: @transaction_token, product_id: @id, quantity: @quantity, value: @value).save!
    product = Product.find(id: @id)
    product.update!(stock_quantity: product.stock_quantity - @quantity)
  end

private

  def _undo_previous_run
    transaction = Transaction.find_by_token(@transaction_token)
    product = Product.find(id: transaction.product_id)
    product.update!(stock_quantity: product.stock_quantity + transaction.quantity)
    transaction.destroy
  end

end

现在我的问题是,应该在哪里测试先前的运行行为?:
BarServiceSpec?
食品管理员规范?(调用创建操作等)
Others ?

最佳答案

测试通常像类api的“文档”一样使用。_undo_previous_run是私有方法,不能直接访问。我更喜欢测试/描述公共方法的行为。
在这种情况下,您需要测试BarService.new方法。

09-25 20:31
查看更多