最佳答案
在提交特性规范中的表单时,我想检查模型中的许多更改。例如,我希望确保用户名从 X 更改为 Y,并且加密的密码被任何值更改。
我知道已经有一些关于这方面的问题,但我没有找到一个适合我的答案。最准确的答案似乎是由迈克尔约翰斯顿在这里的 ChangeMultiple
匹配: 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
匹配器的基本框架,如下所示:
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'
Any help in creating this custom matcher is highly appreciated.