From 60847d6d5d983aa4b0e1fdd265fb5e98c973cc29 Mon Sep 17 00:00:00 2001 From: Esteban Pastorino Date: Mon, 6 Feb 2017 18:54:07 +0100 Subject: [PATCH] Update rspec matcher to work with custom version association names `have_a_version_with` and `have_a_version_with_changes` had the `versions` association call hardcoded. If `has_paper_trail` had the `versions` option set to something else (e.g: `has_paper_trail versions: :paper_trail_versions`) the matcher couldn't be used. This fixes that issue by dynamically fetching the association name from the `:versions_association_name` class attribute. --- CHANGELOG.md | 3 ++- lib/paper_trail/frameworks/rspec.rb | 10 ++++++++-- spec/models/document_spec.rb | 21 +++++++++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 spec/models/document_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 0479dcde..d05c2f6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,8 @@ recommendations of [keepachangelog.com](http://keepachangelog.com/). ### Fixed -- None +- [#925](https://github.com/airblade/paper_trail/pull/925) - Update RSpec + matchers to work with custom version association names ## 6.0.2 (2016-12-13) diff --git a/lib/paper_trail/frameworks/rspec.rb b/lib/paper_trail/frameworks/rspec.rb index a03f544f..3fc5c1fe 100644 --- a/lib/paper_trail/frameworks/rspec.rb +++ b/lib/paper_trail/frameworks/rspec.rb @@ -25,10 +25,16 @@ end RSpec::Matchers.define :have_a_version_with do |attributes| # check if the model has a version with the specified attributes - match { |actual| actual.versions.where_object(attributes).any? } + match do |actual| + versions_association = actual.class.versions_association_name + actual.send(versions_association).where_object(attributes).any? + end end RSpec::Matchers.define :have_a_version_with_changes do |attributes| # check if the model has a version changes with the specified attributes - match { |actual| actual.versions.where_object_changes(attributes).any? } + match do |actual| + versions_association = actual.class.versions_association_name + actual.send(versions_association).where_object_changes(attributes).any? + end end diff --git a/spec/models/document_spec.rb b/spec/models/document_spec.rb new file mode 100644 index 00000000..f150acb5 --- /dev/null +++ b/spec/models/document_spec.rb @@ -0,0 +1,21 @@ +require "rails_helper" + +describe Document, type: :model do + describe "`have_a_version_with` matcher", versioning: true do + it "works with custom versions association" do + document = Document.create!(name: "Foo") + document.update_attributes!(name: "Bar") + + expect(document).to have_a_version_with(name: "Foo") + end + end + + describe "`have_a_version_with_changes` matcher", versioning: true do + it "works with custom versions association" do + document = Document.create!(name: "Foo") + document.update_attributes!(name: "Bar") + + expect(document).to have_a_version_with_changes(name: "Bar") + end + end +end