How to test for (ActiveRecord) object equality

前端 未结 6 1295
礼貌的吻别
礼貌的吻别 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:13

    If like me you're looking for a Minitest answer to this question then here's a custom method that asserts that the attributes of two objects are equal.

    It assumes that you always want to exclude the id, created_at, and updated_at attributes, but you can override that behaviour if you wish.

    I like to keep my test_helper.rb clean so created a test/shared/custom_assertions.rb file with the following content.

    module CustomAssertions
      def assert_attributes_equal(original, new, except: %i[id created_at updated_at])
        extractor = proc { |record| record.attributes.with_indifferent_access.except(*except) }
        assert_equal extractor.call(original), extractor.call(new)
      end
    end
    

    Then alter your test_helper.rb to include it so you can access it within your tests.

    require 'shared/custom_assertions'
    
    class ActiveSupport::TestCase
      include CustomAssertions
    end
    

    Basic usage:

    test 'comments should be equal' do
      assert_attributes_equal(Comment.first, Comment.second)
    end
    

    If you want to override the attributes it ignores then pass an array of strings or symbols with the except arg:

    test 'comments should be equal' do
      assert_attributes_equal(
        Comment.first, 
        Comment.second, 
        except: %i[id created_at updated_at edited_at]
      )
    end
    

提交回复
热议问题