How can I verify that no attribute on the model has been changed using rspec?

I want to check if the attributes of the ActiveRecord object have been changed. I am currently doing this:

prev_attr = obj.attributes <- this will return a hash with the name attr and the value attr

And then, later, I'll take the attributes again and compare the 2 hashes. Is there another way?

+3
source share
3 answers

You just have to use equality equalizers - does this not work for you?

a = { :test => "a" }
b = { :test => "b" }
$ a == b
=> false
b = { :test => "a" }
$ a == b
=> true

Or use your example:

original_attributes = obj.attributes
# do something that should *not* manipulate obj
new_attributes = obj.attributes
new_attributes.should eql original_attributes
+2
source

There is another way. You can do it as follows:

it "should not change sth" do
  expect {
    # some action
  }.to_not change{subject.attribute}
end

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

+6
source

ActiveRecord:: Dirty. changed? , , - , . _changed? , . model.subject_changed?, , , .

, model.subject_was, , . model.changes, 2- , .

+3

All Articles