Kevin
Kevin

Reputation: 15934

Test that a record is a duplicate of another record in RSpec

In my Rails app tested with RSpec, I'm testing a function that calls .dup() on some records and saves the duplicates. How can I test that the newly created records are duplicates of the expected original records?

I doubt there's an assertion for this specific case. And I can always make sure that the duplicate and original records have the same values for their attributes but are different records. I'm wondering if there's a more elegant, accepted pattern for this kind of test.

Upvotes: 0

Views: 1321

Answers (2)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You can use the have_attributes assertion.

match_attributes = first_user.attributes.except(:id, :created_at, :updated_at)

expect(second_user).to have_attributes(match_attributes)

Upvotes: 8

engineersmnky
engineersmnky

Reputation: 29308

You could go about it like so:

 it 'creates a duplicate' do 
    record = Record.find(1) 
    new_record = record.dup
    new_record.save 
    expect(Record.where(id: [record.id,new_record.id], 
           **new_record.attributes.except(:id, :created_at, :updated_at)
           ).count
    ).to eq 2
 end

This should quantify the duplication and persistence of both records in one shot.

Upvotes: 0

Related Questions