在功能规范中提交表单时,我想判断模型中的许多更改.例如,我想确保用户名从X更改为Y,并且加密密码更改了任何值.

我知道已经有一些问题了,但我没有找到适合我的答案.最准确的答案似乎是迈克尔·约翰斯顿的ChangeMultiple matcher:Is it possible for RSpec to expect change in two tables?.它的缺点是只判断从已知值到已知值的显式更改.

我创建了一些伪代码,说明我认为更好的匹配器应该是什么样子:

expect {
  click_button 'Save'
}.to change_multiple { @user.reload }.with_expectations(
  name:               {from: 'donald', to: 'gustav'},
  updated_at:         {by: 4},
  great_field:        {by_at_leaset: 23},
  encrypted_password: true,  # Must change
  created_at:         false, # Must not change
  some_other_field:   nil    # Doesn't matter, but want to denote here that this field exists
)

我还创建了ChangeMultiple matcher的基本框架,如下所示:

module RSpec
  module Matchers
    def change_multiple(receiver=nil, message=nil, &block)
      BuiltIn::ChangeMultiple.new(receiver, message, &block)
    end

    module BuiltIn
      class ChangeMultiple < Change
        def with_expectations(expectations)
          # What to do here? How do I add the expectations passed as argument?
        end
      end
    end
  end
end

但现在我已经发现了这个错误:

 Failure/Error: expect {
   You must pass an argument rather than a block to use the provided matcher (nil), or the matcher must implement `supports_block_expectations?`.
 # ./spec/features/user/registration/edit_spec.rb:20:in `block (2 levels) in <top (required)>'
 # /Users/josh/.rvm/gems/ruby-2.1.0@base/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in `load'
 # /Users/josh/.rvm/gems/ruby-2.1.0@base/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in `block in load'

非常感谢您对创建此定制匹配器的任何帮助.

推荐答案

在RSpec 3中,您可以一次设置多个条件(这样就不会违反单一期望规则).它看起来像:

expect {
  click_button 'Save'
  @user.reload
}.to change { @user.name }.from('donald').to('gustav')
 .and change { @user.updated_at }.by(4)
 .and change { @user.great_field }.by_at_least(23}
 .and change { @user.encrypted_password }

不过,这并不是一个完整的解决方案——就我的研究而言,还没有简单的方法.我也不确定你最后的判断结果(如果没关系,为什么要测试?).当然,你应该能够在custom matcher分钟内完成.

Ruby-on-rails相关问答推荐

Ruby on rails Admin-有没有一种方法可以在成对的管理控制器类中合并、重用应用程序控制器类?

Ubuntu Webhooks无法读取安装的正确RVM Ruby

Rails版本7.1.2:当验证失败且控制器发送422状态时,JS停止工作

如何将 ActionController::RoutingError 分类为 Sentry 中的错误

ActiveRecord 错误地转义 JSON 字符串

在 JS 模块中使用 Rails-UJS(带有 webpacker 的 Rails 6)

如何在 Rails 中使用 instance_eval 子句删除验证?

如何在 rspec 中运行单个测试?

Rails - 获取没有 GET 参数的当前 url

具有 has_many 关联的 FactoryGirl build_stubbed 策略

使用god 监控独角兽 - 以非零代码开始退出 = 1

关于在不适合任何地方的 Rails 应用程序中放置类的指南

保存后重定向到索引而不是显示

Rails SQL 正则表达式

Rails 4模块的未初始化常量

如何创建迁移以仅在索引存在时删除索引,而不是在不存在时抛出异常?

ruby 方法名称中的变量

Rails 路由:GET 没有参数 :id

未捕获的 ReferenceError:未定义 ReactDOM

为什么 rails bootstrap 这么慢,我该怎么办?