如何测试使用rspec修改模型上的任何属性?

Geo*_*Geo 4 rspec ruby-on-rails

我想检查ActiveRecord对象上是否没有修改任何属性.目前我这样做:

prev_attr = obj.attributes < - 这将给我一个带有attr名称和attr值的哈希

然后,稍后,我再次获取属性并比较两个哈希值.还有另外一种方法吗?

tho*_*ron 8

确实有另一种方式.你可以这样做:

it "should not change sth" do
  expect {
    # some action
  }.to_not change{subject.attribute}
end
Run Code Online (Sandbox Code Playgroud)

请参阅https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/expect-change.


Rob*_*per 2

您应该能够使用相等匹配器- 这对您不起作用吗?

a = { :test => "a" }
b = { :test => "b" }
$ a == b
=> false
b = { :test => "a" }
$ a == b
=> true
Run Code Online (Sandbox Code Playgroud)

或者使用你的例子:

original_attributes = obj.attributes
# do something that should *not* manipulate obj
new_attributes = obj.attributes
new_attributes.should eql original_attributes
Run Code Online (Sandbox Code Playgroud)