【问题标题】:Testing Cells in isolation with Rspec - any recommandation?使用 Rspec 隔离测试细胞 - 有什么建议吗?
【发布时间】:2015-01-29 22:06:06
【问题描述】:

我正在尝试使用 Apotonick 的 Trailblazer gem,它在 Rails 之上带来了更多的结构,我真的很喜欢我迄今为止尝试过的东西,但还没有完全接受它。这是 Trailblazer 的一大优势,您可以逐步深入了解它,逐步将其引入您的 Rails 项目。我买了 Trailblazer 这本书,我现在正在关注这本书,这引出了我的问题。

我正在开发示例应用程序 (@see https://github.com/apotonick/gemgem-trbrb),但我正在使用 rspec。

我想单独测试单元格输出。在本书中,测试框架是 Test::Unit,一些辅助方法附带了 Test::Unit 的单元格。

使用 rspec 是另一回事......我尝试了 rspec-cells,但它似乎不适用于 Trailblazer 中使用的当前单元版本 (4.0)。 因此,我尝试进行一些鲑鱼编码,目标是尽可能使用最小的设置来检索单元格的输出。这导致了一个带有简单助手的模块

这是代码(也在这里:https://github.com/demental/gemgem-trbrb/blob/3ec9df1d5f45b880f834486da3c150d4b65ec627/spec/support/cells.rb

module Cell
  module Rspec
    private
    def concept(name, *args)
      controller_stub = double(
        url_options: {
          host: '',
          optional_port: 80,
          protocol: 'http',
          path_parameters: ''
        }
      )
      Capybara.string(Cell::Concept.cell name, controller_stub, *args)
    end
  end
end

RSpec.configure do |config|
  config.include Cell::Rspec, type: :cell
end

我需要创建一个存根的 url_options 方法的原因是 pathHelpers 方法可以在单元格视图中工作,而无需设置完整的控制器(带有完整的请求对象)。

我喜欢它,因为它的设置非常简约。但我想知道它是不是太假了,因为我只是模仿一个控制器,但我觉得我没有摆脱它的依赖。你怎么看?

【问题讨论】:

    标签: ruby-on-rails rspec rails-cells trailblazer


    【解决方案1】:

    我知道这篇文章很旧,但我看到你的代码中仍然没有解决问题。

    cell方法的第三个参数需要添加controller,因为cell中的第二个参数是model,第三个是options。你可以这样做:

    controller_stub = double(
      url_options: {
        host: '',
        optional_port: 80,
        protocol: 'http',
        path_parameters: ''
      }
    )
    args[1] = {} if args.length < 2
    args[1].merge! controller: controller_stub
    Capybara.string(Cell::Concept.cell(name, *args).to_s)
    

    方法 Cell::Concept.cell 只是 ViewModel.cell 的包装,当您查看此方法时,您可以看到它在 options 参数中添加了控制器:

    def cell(name, model=nil, options={})
      ViewModel.cell(name, model, options.merge(controller: parent_controller))
    end
    

    更深入的 parent_controller 在 ViewModel 类中定义并在构造函数中初始化:

    def initialize(model=nil, options={})
      @parent_controller = options[:controller]
    
      setup!(model, options)
    end
    attr_reader :parent_controller
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2010-09-20
      • 2014-07-05
      • 2018-03-21
      相关资源
      最近更新 更多