【问题标题】:How to use ActiveModel::Lint::Tests in Rspec如何在 Rspec 中使用 ActiveModel::Lint::Tests
【发布时间】:2015-06-26 21:54:21
【问题描述】:

对于默认 Rails,您可以添加所谓的 ActiveModel::Lint::Tests 以查看您的模型是否符合 ActiveModel 的某些部分。

我想在我的 Rspec 测试中调用这些或等效的名称。

  • 我不想测试确切的行为:lint 测试仅说明存在某个接口。我只想说明接口存在。
  • 我宁愿不test too close implementation。仅仅测试包含的模块与测试存在的接口并不完全相同。

在 rspec 示例中运行和包含 Rails 核心 ActiveModel::Lint::Tests 是否有技巧?是否有专门为 Rspec 构建的替代方案来运行此类 lint 测试?

一些背景

我正在构建的模型不继承自 Activerecord::Base,而是充当工厂或状态机。在 Rails 中也称为服务对象。这些对用户来说应该感觉像是 ActiveModel。像

@services << CompositeService.new(name: 'foo', children: [{ name: 'bar' }])
render @services

应该是可以的。那么这样的CompositeService 应该有activemodel 命名、部分路径、caching-ids 等等。

【问题讨论】:

    标签: rspec activemodel lint


    【解决方案1】:

    我正在编写一个提供 ActiveModel 兼容模型并使用 RSpec 3.x 的 gem。

    为了获得 lint 测试,我添加了 activemodel 作为开发依赖项。这也带来了ActiveSupportMinitest。我想我可以像过去一样使用this gist 之类的东西,但遇到了issue 试图让测试使用Minitestassert

    我最终把它放在一起(感谢主旨的作者)并将其放入spec/support

    require 'active_model/lint'
    require 'minitest'
    
    RSpec.shared_examples_for ActiveModel do
      include ActiveModel::Lint::Tests
      include Minitest::Assertions
    
      alias_method :model, :subject
    
      attr_accessor :assertions
    
      before(:each) { self.assertions = 0 }
    
      ActiveModel::Lint::Tests.public_instance_methods.map(&:to_s).grep(/^test/).each do |m|
        it(m.sub 'test_', 'responds to ') { send m }
      end
    end
    

    到目前为止,这似乎有效,我收到如下错误消息:

    Failure/Error: it(m.sub 'test_', 'responds to ') { send m }
    Minitest::Assertion:
     The model should respond to to_key
    

    这并不理想,但我现在还可以。 lint 测试非常简单 从头开始实现共享示例将非常简单 (请参阅the source),但这样我就可以依靠 gem 来保持测试最新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多