如何在Rspec中使用ActiveModel::Lint::Tests
对于默认的Rails,您可以添加所谓的来查看您的模型是否符合ActiveModel的部分 我想在我的Rspec测试中称之为这些,或其等价物如何在Rspec中使用ActiveModel::Lint::Tests,rspec,activemodel,lint,Rspec,Activemodel,Lint,对于默认的Rails,您可以添加所谓的来查看您的模型是否符合ActiveModel的部分 我想在我的Rspec测试中称之为这些,或其等价物 我不想测试确切的行为:lint只测试特定接口存在的规范。我只想说明接口是否存在 我宁愿不要。仅仅测试模块是否包含与测试接口是否存在并不完全相同 在rspec示例中运行并包含Rails核心ActiveModel::Lint::Tests有什么诀窍吗?是否有专门为运行此类lint测试的Rspec构建的替代方案 一些背景: 我正在构建的模型不是继承自Activ
- 我不想测试确切的行为:lint只测试特定接口存在的规范。我只想说明接口是否存在
- 我宁愿不要。仅仅测试模块是否包含与测试接口是否存在并不完全相同
ActiveModel::Lint::Tests
有什么诀窍吗?是否有专门为运行此类lint测试的Rspec构建的替代方案
一些背景:
我正在构建的模型不是继承自Activerecord::Base
,而是充当工厂或状态机。在Rails中,也称为服务对象。对于用户来说,这些应该是ActiveModels。诸如此类
@services << CompositeService.new(name: 'foo', children: [{ name: 'bar' }])
render @services
@services我正在编写一个gem,它提供符合ActiveModel
的模型,并使用rspec3.x
为了获得lint测试,我添加了activemodel
作为开发依赖项。这也带来了ActiveSupport
和Minitest
。我想我可以像过去一样使用一些东西,但在尝试让测试使用Minitest
的assert
时遇到了一个问题
最后我把它放在一起(归功于本文作者),并将其放入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
这并不理想,但我现在还可以。皮棉测试非常简单
从零开始实现一个共享示例是非常简单的
(请参阅),但这样我就可以依靠gem使测试保持最新