ruby - Controller 使用的测试服务的正确方法

标签 ruby ruby-on-rails-4 rspec tdd

给定以下代码:

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

现在我的问题是,测试 _undo_previous_run 行为的正确位置应该在哪里?:

  • BarServiceSpec?
  • FooControllerSpec? (调用创建操作等)
  • 其他?

最佳答案

测试通常用作类 API 的“文档”。 _undo_previous_run是私有(private)方法,不能直接访问。我更喜欢测试/描述公共(public)方法的行为。

在这种情况下,您需要测试 BarService.new 方法。

关于ruby - Controller 使用的测试服务的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38161773/

相关文章:

ruby - 用散列中的值替换键

ruby - 为什么保存在这里失败,SQLite3::ConstraintException: column user_id is not unique: INSERT INTO "pins"?

javascript - 在 Rails 中使用 ajax、jquery 在同一位置提交编辑后的评论

ruby-on-rails - RoR - rspec 测试失败,不应该

c++ - Ruby win32 API 接口(interface)

ruby-on-rails - 如何删除 ".each do "中的重复元素?

ruby-on-rails-3 - 在 rspec 中,我能否确保某些示例仅在另一个示例通过时运行?

ruby-on-rails - Draper - NoMethodError 与装饰器的 RSpec 测试

ruby-on-rails - 将 ruby 链接到 RVM

ruby-on-rails - 为什么 rails server Welcome Aboard 站点向 rbenv 报告不同的 ruby​​ 版本?