Back to Repositories

Testing Model Version History Implementation in Paper Trail

This test suite validates the versioning functionality of the Car model in PaperTrail, focusing on changeset tracking and attribute reification. It ensures proper version history management and attribute handling across different model states.

Test Coverage Overview

The test suite provides comprehensive coverage of PaperTrail’s versioning capabilities for the Car model. Key areas tested include:

  • Versioning activation verification
  • Changeset key validation
  • Non-ActiveRecord attribute reification
  • Historical attribute restoration

Implementation Analysis

The testing approach uses RSpec’s behavior-driven development patterns with focused contexts for different versioning scenarios. It leverages PaperTrail’s versioning: true shared context and employs expect/assert syntax for assertions. The implementation demonstrates proper use of described_class and version history manipulation.

Technical Details

  • Testing Framework: RSpec
  • ORM: ActiveRecord
  • Versioning Library: PaperTrail
  • Serialization: YAML
  • Test Environment: Isolated versioning context

Best Practices Demonstrated

The test suite exemplifies several testing best practices including isolated test contexts, clear test descriptions, and proper setup of test scenarios. It demonstrates effective use of RSpec’s shared contexts, proper model versioning validation, and comprehensive attribute tracking verification.

paper-trail-gem/paper_trail

spec/models/car_spec.rb

            
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Car, type: :model do
  it { is_expected.to be_versioned }

  describe "changeset", versioning: true do
    it "has the expected keys (see issue 738)" do
      car = described_class.create!(name: "Alice")
      car.update(name: "Bob")
      assert_includes car.versions.last.changeset.keys, "name"
    end
  end

  describe "attributes and accessors", versioning: true do
    it "reifies attributes that are not AR attributes" do
      car = described_class.create name: "Pinto", color: "green"
      car.update color: "yellow"
      car.update color: "brown"
      expect(car.versions.second.reify.color).to eq("yellow")
    end

    it "reifies attributes that once were attributes but now just attr_accessor" do
      car = described_class.create name: "Pinto", color: "green"
      car.update color: "yellow"
      changes = PaperTrail::Serializers::YAML.load(car.versions.last.attributes["object"])
      changes[:top_speed] = 80
      car.versions.first.update object: changes.to_yaml
      car.reload
      expect(car.versions.first.reify.top_speed).to eq(80)
    end
  end
end