How to test for (ActiveRecord) object equality

前端 未结 6 1283
礼貌的吻别
礼貌的吻别 2020-11-29 05:55

In Ruby 1.9.2 on Rails 3.0.3, I\'m attempting to test for object equality between two Friend (class inherits from ActiveRecord::

6条回答
  •  渐次进展
    2020-11-29 06:14

    I created a matcher on RSpec just for this type of comparison, very simple, but effective.

    Inside this file: spec/support/matchers.rb

    You can implement this matcher...

    RSpec::Matchers.define :be_a_clone_of do |model1|
      match do |model2|
        ignored_columns = %w[id created_at updated_at]
        model1.attributes.except(*ignored_columns) == model2.attributes.except(*ignored_columns)
      end
    end
    

    After that, you can use it when writing a spec, by the following way...

    item = create(:item) # FactoryBot gem
    item2 = item.dup
    
    expect(item).to be_a_clone_of(item2)
    # True
    

    Useful links:

    https://relishapp.com/rspec/rspec-expectations/v/2-4/docs/custom-matchers/define-matcher https://github.com/thoughtbot/factory_bot

提交回复
热议问题