Break long lines in `test` dir

This commit is contained in:
Jared Beck 2016-02-15 18:13:45 -05:00
parent ddf7f45ff4
commit 0d7e33eb2e
23 changed files with 401 additions and 171 deletions

View File

@ -1,9 +1,27 @@
inherit_from: .rubocop_todo.yml inherit_from: .rubocop_todo.yml
# Please:
#
# - Comment any deviations from the Ruby Style Guide
# - Alphabetize cops
# - Only include permanent config; temporary goes in .rubocop_todo.yml
# We do not control `schema.rb`. Exclude it from all cops.
AllCops: AllCops:
Exclude: Exclude:
- 'spec/**/*' - test/dummy/db/schema.rb
- 'test/**/*'
# The Ruby Style Guide recommends to "Limit lines to 80 characters."
# (https://github.com/bbatsov/ruby-style-guide#80-character-limits)
# but 100 is also reasonable.
Metrics/LineLength:
Max: 100
# Migrations often contain long up/down methods, and extracting smaller methods
# from these is of questionable value.
Metrics/MethodLength:
Exclude:
- 'test/dummy/db/migrate/*'
Style/AlignParameters: Style/AlignParameters:
EnforcedStyle: with_fixed_indentation EnforcedStyle: with_fixed_indentation
@ -24,6 +42,3 @@ Style/DotPosition:
# concatenate multiline strings with `+` or use a HEREDOC. # concatenate multiline strings with `+` or use a HEREDOC.
Style/LineEndConcatenation: Style/LineEndConcatenation:
Enabled: false Enabled: false
Metrics/LineLength:
Max: 100

View File

@ -1,10 +1,5 @@
# This configuration was generated by # Remove these configuration records
# `rubocop --auto-gen-config`
# on 2016-02-15 16:48:20 -0500 using RuboCop version 0.37.2.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base. # one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 3 # Offense count: 3
Lint/AmbiguousRegexpLiteral: Lint/AmbiguousRegexpLiteral:
@ -89,16 +84,16 @@ Metrics/BlockNesting:
# Configuration parameters: CountComments. # Configuration parameters: CountComments.
Metrics/ClassLength: Metrics/ClassLength:
Max: 1106 Max: 1106
Exclude:
- test/**/*
# Offense count: 6 # Offense count: 6
Metrics/CyclomaticComplexity: Metrics/CyclomaticComplexity:
Max: 13 Max: 13
# Offense count: 463
# Configuration parameters: AllowHeredoc, AllowURI, URISchemes.
# URISchemes: http, https
Metrics/LineLength: Metrics/LineLength:
Max: 187 Exclude:
- spec/**/*
# Offense count: 18 # Offense count: 18
# Configuration parameters: CountComments. # Configuration parameters: CountComments.

View File

@ -1,5 +1,12 @@
class Article < ActiveRecord::Base class Article < ActiveRecord::Base
has_paper_trail :ignore => [:title, { :abstract => Proc.new { |obj| ['ignore abstract', 'Other abstract'].include? obj.abstract } } ], has_paper_trail(
:ignore => [
:title, {
:abstract => Proc.new { |obj|
['ignore abstract', 'Other abstract'].include? obj.abstract
}
}
],
:only => [:content, { :abstract => Proc.new { |obj| obj.abstract.present? } } ], :only => [:content, { :abstract => Proc.new { |obj| obj.abstract.present? } } ],
:skip => [:file_upload], :skip => [:file_upload],
:meta => { :meta => {
@ -9,6 +16,7 @@ class Article < ActiveRecord::Base
:article_id => Proc.new { |article| article.id }, :article_id => Proc.new { |article| article.id },
:title => :title :title => :title
} }
)
def action_data_provider_method def action_data_provider_method
self.object_id.to_s self.object_id.to_s

View File

@ -7,7 +7,8 @@ class Widget < ActiveRecord::Base
validates :name, :exclusion => { :in => [EXCLUDED_NAME] } validates :name, :exclusion => { :in => [EXCLUDED_NAME] }
if ::ActiveRecord::VERSION::MAJOR >= 4 # `has_many` syntax for specifying order uses a lambda in Rails 4 # `has_many` syntax for specifying order uses a lambda in Rails 4
if ::ActiveRecord::VERSION::MAJOR >= 4
has_many :fluxors, lambda { order(:name) } has_many :fluxors, lambda { order(:name) }
else else
has_many :fluxors, :order => :name has_many :fluxors, :order => :name

View File

@ -1,5 +1,6 @@
# The purpose of this custom version class is to test the scope methods on the VersionConcern::ClassMethods # The purpose of this custom version class is to test the scope methods on the
# module. See https://github.com/airblade/paper_trail/issues/295 for more details. # VersionConcern::ClassMethods module. See
# https://github.com/airblade/paper_trail/issues/295 for more details.
class JoinedVersion < PaperTrail::Version class JoinedVersion < PaperTrail::Version
default_scope { joins('INNER JOIN widgets ON widgets.id = versions.item_id') } default_scope { joins('INNER JOIN widgets ON widgets.id = versions.item_id') }
end end

View File

@ -49,7 +49,9 @@ module Dummy
# This will create an empty whitelist of attributes available for mass-assignment for all models # This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration. # parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = false if ::PaperTrail.active_record_protected_attributes? if ::PaperTrail.active_record_protected_attributes?
config.active_record.whitelist_attributes = false
end
# `config.assets` is a `NoMethodError` in rails 5. # `config.assets` is a `NoMethodError` in rails 5.
if config.respond_to?(:assets) if config.respond_to?(:assets)

View File

@ -23,7 +23,9 @@ Dummy::Application.configure do
config.action_dispatch.best_standards_support = :builtin config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models # Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict if ::PaperTrail.active_record_protected_attributes? if ::PaperTrail.active_record_protected_attributes?
config.active_record.mass_assignment_sanitizer = :strict
end
# Log the query plan for queries taking more than this (works # Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL) # with SQLite, MySQL, and PostgreSQL)

View File

@ -51,7 +51,8 @@ Dummy::Application.configure do
# Enable serving of images, stylesheets, and JavaScripts from an asset server # Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com" # config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # Precompile additional assets (application.js, application.css, and all
# non-JS/CSS are already added)
# config.assets.precompile += %w( search.js ) # config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored # Disable delivery errors, bad email addresses will be ignored

View File

@ -42,7 +42,9 @@ Dummy::Application.configure do
# config.action_mailer.delivery_method = :test # config.action_mailer.delivery_method = :test
# Raise exception on mass assignment protection for Active Record models # Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict if ::PaperTrail.active_record_protected_attributes? if ::PaperTrail.active_record_protected_attributes?
config.active_record.mass_assignment_sanitizer = :strict
end
# Print deprecation notices to the stderr # Print deprecation notices to the stderr
config.active_support.deprecation = :stderr config.active_support.deprecation = :stderr

View File

@ -1,7 +1,9 @@
# Be sure to restart your server when you modify this file. # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # You can add backtrace silencers for libraries that you're using but don't wish
# to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # You can also remove all the silencers if you're trying to debug a problem that
# might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers! # Rails.backtrace_cleaner.remove_silencers!

View File

@ -4,4 +4,6 @@
# If you change this key, all old signed cookies will become invalid! # If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random, # Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks. # no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_token = '99c0312cf416079a8c7ccc63acb1e9f4f17741398ec8022a2f4fb509c57f55b72486573e9816a026f507efbcd452a9e954d45c93c95d5bacd87e664ad6805d3f' Dummy::Application.config.secret_token = '99c0312cf416079a8c7ccc63acb1e9f4f' +
'17741398ec8022a2f4fb509c57f55b72486573e9816a026f507efbcd452a9e954d45c93c' +
'95d5bacd87e664ad6805d3f'

View File

@ -50,7 +50,9 @@ class SetUpTestTables < ActiveRecord::Migration
t.integer :foreign_key_id t.integer :foreign_key_id
end end
add_index :version_associations, [:version_id] add_index :version_associations, [:version_id]
add_index :version_associations, [:foreign_key_name, :foreign_key_id], :name => 'index_version_associations_on_foreign_key' add_index :version_associations,
[:foreign_key_name, :foreign_key_id],
:name => 'index_version_associations_on_foreign_key'
create_table :post_versions, :force => true do |t| create_table :post_versions, :force => true do |t|
t.string :item_type, :null => false t.string :item_type, :null => false

View File

@ -1,5 +1,7 @@
#!/usr/bin/env ruby #!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
# This command will automatically be run when you run "rails" with Rails 3 gems
# installed from the root of your application.
APP_PATH = File.expand_path('../../config/application', __FILE__) APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__) require File.expand_path('../../config/boot', __FILE__)

View File

@ -70,7 +70,7 @@ class ControllerTest < ActionController::TestCase
assert_equal 153, widget.versions.last.whodunnit.to_i assert_equal 153, widget.versions.last.whodunnit.to_i
end end
test "controller metadata methods should get evaluated if paper trail is enabled for controller" do test "controller metadata methods should get evaluated if PT enabled for controller" do
@request.env['HTTP_USER_AGENT'] = 'User-Agent' @request.env['HTTP_USER_AGENT'] = 'User-Agent'
post :create, params_wrapper({ widget: { name: 'Flugel' } }) post :create, params_wrapper({ widget: { name: 'Flugel' } })
assert PaperTrail.enabled_for_controller? assert PaperTrail.enabled_for_controller?
@ -80,7 +80,7 @@ class ControllerTest < ActionController::TestCase
assert PaperTrail.controller_info.keys.include?(:user_agent) assert PaperTrail.controller_info.keys.include?(:user_agent)
end end
test "controller metadata methods should not get evaluated if paper trail is disabled for controller" do test "controller metadata methods should not get evaluated if PT disabled for controller" do
@request.env['HTTP_USER_AGENT'] = 'Disable User-Agent' @request.env['HTTP_USER_AGENT'] = 'Disable User-Agent'
post :create, params_wrapper({ widget: { name: 'Flugel' } }) post :create, params_wrapper({ widget: { name: 'Flugel' } })
assert_equal 0, assigns(:widget).versions.length assert_equal 0, assigns(:widget).versions.length

View File

@ -15,7 +15,10 @@ if Gem::Version.new(Rack.release) < Gem::Version.new("2.0.0.alpha")
configs = YAML.load_file(File.expand_path('../../dummy/config/database.yml', __FILE__)) configs = YAML.load_file(File.expand_path('../../dummy/config/database.yml', __FILE__))
ActiveRecord::Base.configurations = configs ActiveRecord::Base.configurations = configs
ActiveRecord::Base.establish_connection(:test) ActiveRecord::Base.establish_connection(:test)
register PaperTrail::Sinatra # we shouldn't actually need this line if I'm not mistaken but the tests seem to fail without it ATM
# We shouldn't actually need this line if I'm not mistaken but the tests
# seem to fail without it ATM
register PaperTrail::Sinatra
get '/test' do get '/test' do
Widget.create!(:name => 'bar') Widget.create!(:name => 'bar')

View File

@ -21,7 +21,11 @@ require 'shoulda'
require 'ffaker' require 'ffaker'
require 'database_cleaner' require 'database_cleaner'
if Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('5.0.0.beta1') def active_record_gem_version
Gem::Version.new(ActiveRecord::VERSION::STRING)
end
if active_record_gem_version >= Gem::Version.new('5.0.0.beta1')
# See https://github.com/rails/rails-controller-testing/issues/5 # See https://github.com/rails/rails-controller-testing/issues/5
ActionController::TestCase.send(:include, Rails::Controller::Testing::TestProcess) ActionController::TestCase.send(:include, Rails::Controller::Testing::TestProcess)
end end
@ -102,7 +106,7 @@ end
# ActionDispatch::Integration HTTP request method switch to keyword args # ActionDispatch::Integration HTTP request method switch to keyword args
# (see https://github.com/rails/rails/blob/master/actionpack/CHANGELOG.md) # (see https://github.com/rails/rails/blob/master/actionpack/CHANGELOG.md)
def params_wrapper(args) def params_wrapper(args)
if defined?(::Rails) && Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('5.0.0.beta1') if defined?(::Rails) && active_record_gem_version >= Gem::Version.new('5.0.0.beta1')
{ params: args } { params: args }
else else
args args

View File

@ -161,9 +161,11 @@ class AssociationsTest < ActiveSupport::TestCase
end end
context 'when reified with option mark_for_destruction' do context 'when reified with option mark_for_destruction' do
setup { @customer_0 = @customer.versions.last.reify(:has_many => true, :mark_for_destruction => true) }
should 'mark the associated for destruction' do should 'mark the associated for destruction' do
@customer_0 = @customer.versions.last.reify(
:has_many => true,
:mark_for_destruction => true
)
assert_equal [true], @customer_0.orders.map(&:marked_for_destruction?) assert_equal [true], @customer_0.orders.map(&:marked_for_destruction?)
end end
end end
@ -293,15 +295,21 @@ class AssociationsTest < ActiveSupport::TestCase
end end
should 'not persist changes to the live association' do should 'not persist changes to the live association' do
assert_equal ['order_date_0', 'order_date_1'], @customer.orders.reload.map(&:order_date).sort assert_equal ['order_date_0', 'order_date_1'],
@customer.orders.reload.map(&:order_date).sort
end end
end end
context 'when reified with option mark_for_destruction' do context 'when reified with option mark_for_destruction' do
setup { @customer_0 = @customer.versions.last.reify(:has_many => true, :mark_for_destruction => true) }
should 'mark the newly associated for destruction' do should 'mark the newly associated for destruction' do
assert @customer_0.orders.detect { |o| o.order_date == 'order_date_1'}.marked_for_destruction? @customer_0 = @customer.versions.last.reify(
:has_many => true,
:mark_for_destruction => true
)
assert @customer_0.
orders.
detect { |o| o.order_date == 'order_date_1'}.
marked_for_destruction?
end end
end end
end end
@ -331,7 +339,12 @@ class AssociationsTest < ActiveSupport::TestCase
end end
context 'when reified with option mark_for_destruction' do context 'when reified with option mark_for_destruction' do
setup { @book_0 = @book.versions.last.reify(:has_many => true, :mark_for_destruction => true) } setup do
@book_0 = @book.versions.last.reify(
:has_many => true,
:mark_for_destruction => true
)
end
should 'mark the associated for destruction' do should 'mark the associated for destruction' do
assert_equal [true], @book_0.authors.map(&:marked_for_destruction?) assert_equal [true], @book_0.authors.map(&:marked_for_destruction?)
@ -352,7 +365,9 @@ class AssociationsTest < ActiveSupport::TestCase
end end
context 'when reified' do context 'when reified' do
setup { @book_0 = @book.versions.last.reify(:has_many => true) } setup do
@book_0 = @book.versions.last.reify(:has_many => true)
end
should 'see the associated as it was at the time' do should 'see the associated as it was at the time' do
assert_equal [], @book_0.authors assert_equal [], @book_0.authors
@ -360,7 +375,12 @@ class AssociationsTest < ActiveSupport::TestCase
end end
context 'when reified with option mark_for_destruction' do context 'when reified with option mark_for_destruction' do
setup { @book_0 = @book.versions.last.reify(:has_many => true, :mark_for_destruction => true) } setup do
@book_0 = @book.versions.last.reify(
:has_many => true,
:mark_for_destruction => true
)
end
should 'not mark the associated for destruction' do should 'not mark the associated for destruction' do
assert_equal [false], @book_0.authors.map(&:marked_for_destruction?) assert_equal [false], @book_0.authors.map(&:marked_for_destruction?)
@ -486,14 +506,25 @@ class AssociationsTest < ActiveSupport::TestCase
end end
context 'when reified with option mark_for_destruction' do context 'when reified with option mark_for_destruction' do
setup { @book_0 = @book.versions.last.reify(:has_many => true, :mark_for_destruction => true) } setup do
@book_0 = @book.versions.last.reify(
:has_many => true,
:mark_for_destruction => true
)
end
should 'mark the newly associated for destruction' do should 'mark the newly associated for destruction' do
assert @book_0.authors.detect { |a| a.name == 'author_1' }.marked_for_destruction? assert @book_0.
authors.
detect { |a| a.name == 'author_1' }.
marked_for_destruction?
end end
should 'mark the newly associated-through for destruction' do should 'mark the newly associated-through for destruction' do
assert @book_0.authorships.detect { |as| as.person.name == 'author_1' }.marked_for_destruction? assert @book_0.
authorships.
detect { |as| as.person.name == 'author_1' }.
marked_for_destruction?
end end
end end
end end
@ -516,14 +547,25 @@ class AssociationsTest < ActiveSupport::TestCase
end end
context 'when reified with option mark_for_destruction' do context 'when reified with option mark_for_destruction' do
setup { @book_0 = @book.versions.last.reify(:has_many => true, :mark_for_destruction => true) } setup do
@book_0 = @book.versions.last.reify(
:has_many => true,
:mark_for_destruction => true
)
end
should 'not mark the newly associated for destruction' do should 'not mark the newly associated for destruction' do
assert !@book_0.authors.detect { |a| a.name == 'person_existing' }.marked_for_destruction? assert !@book_0.
authors.
detect { |a| a.name == 'person_existing' }.
marked_for_destruction?
end end
should 'mark the newly associated-through for destruction' do should 'mark the newly associated-through for destruction' do
assert @book_0.authorships.detect { |as| as.person.name == 'person_existing' }.marked_for_destruction? assert @book_0.
authorships.
detect { |as| as.person.name == 'person_existing' }.
marked_for_destruction?
end end
end end
end end

View File

@ -29,9 +29,10 @@ class PaperTrailCleanerTest < ActiveSupport::TestCase
end end
should 'removes the earliest version(s)' do should 'removes the earliest version(s)' do
most_recent_version_names = @animals.map { |animal| animal.versions.last.reify.name } before = @animals.map { |animal| animal.versions.last.reify.name }
PaperTrail.clean_versions! PaperTrail.clean_versions!
assert_equal most_recent_version_names, @animals.map { |animal| animal.versions.last.reify.name } after = @animals.map { |animal| animal.versions.last.reify.name }
assert_equal before, after
end end
end end
@ -103,31 +104,37 @@ class PaperTrailCleanerTest < ActiveSupport::TestCase
should 'restrict cleaning properly' do should 'restrict cleaning properly' do
PaperTrail.clean_versions!(:date => @date, :keeping => 2) PaperTrail.clean_versions!(:date => @date, :keeping => 2)
[@animal, @dog].each do |animal| [@animal, @dog].each do |animal|
animal.versions.reload # reload the association to pick up the destructions made by the `Cleaner` # reload the association to pick up the destructions made by the `Cleaner`
animal.versions.reload
assert_equal 3, animal.versions.size assert_equal 3, animal.versions.size
assert_equal 2, animal.versions.between(@date, @date+1.day).size assert_equal 2, animal.versions.between(@date, @date+1.day).size
end end
assert_equal 9, PaperTrail::Version.count # ensure that the versions for the `@cat` instance wasn't touched # ensure that the versions for the `@cat` instance wasn't touched
assert_equal 9, PaperTrail::Version.count
end end
end end
context 'and `:item_id`' do context 'and `:item_id`' do
should 'restrict cleaning properly' do should 'restrict cleaning properly' do
PaperTrail.clean_versions!(:date => @date, :item_id => @dog.id) PaperTrail.clean_versions!(:date => @date, :item_id => @dog.id)
@dog.versions.reload # reload the association to pick up the destructions made by the `Cleaner` # reload the association to pick up the destructions made by the `Cleaner`
@dog.versions.reload
assert_equal 2, @dog.versions.size assert_equal 2, @dog.versions.size
assert_equal 1, @dog.versions.between(@date, @date+1.day).size assert_equal 1, @dog.versions.between(@date, @date+1.day).size
assert_equal 9, PaperTrail::Version.count # ensure the versions for other animals besides `@animal` weren't touched # ensure the versions for other animals besides `@animal` weren't touched
assert_equal 9, PaperTrail::Version.count
end end
end end
context ', `:item_id`, and `:keeping`' do context ', `:item_id`, and `:keeping`' do
should 'restrict cleaning properly' do should 'restrict cleaning properly' do
PaperTrail.clean_versions!(:date => @date, :item_id => @dog.id, :keeping => 2) PaperTrail.clean_versions!(:date => @date, :item_id => @dog.id, :keeping => 2)
@dog.versions.reload # reload the association to pick up the destructions made by the `Cleaner` # reload the association to pick up the destructions made by the `Cleaner`
@dog.versions.reload
assert_equal 3, @dog.versions.size assert_equal 3, @dog.versions.size
assert_equal 2, @dog.versions.between(@date, @date+1.day).size assert_equal 2, @dog.versions.between(@date, @date+1.day).size
assert_equal 10, PaperTrail::Version.count # ensure the versions for other animals besides `@animal` weren't touched # ensure the versions for other animals besides `@animal` weren't touched
assert_equal 10, PaperTrail::Version.count
end end
end end
end end
@ -136,7 +143,8 @@ class PaperTrailCleanerTest < ActiveSupport::TestCase
should 'restrict cleaning properly' do should 'restrict cleaning properly' do
PaperTrail.clean_versions!(:keeping => 2, :item_id => @animal.id) PaperTrail.clean_versions!(:keeping => 2, :item_id => @animal.id)
assert_equal 2, @animal.versions.size assert_equal 2, @animal.versions.size
assert_equal 8, PaperTrail::Version.count # ensure the versions for other animals besides `@animal` weren't touched # ensure the versions for other animals besides `@animal` weren't touched
assert_equal 8, PaperTrail::Version.count
end end
end end
end end

View File

@ -5,58 +5,82 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
context "A record with defined 'only' and 'ignore' attributes" do context "A record with defined 'only' and 'ignore' attributes" do
setup { @article = Article.create } setup { @article = Article.create }
should 'creation should change the number of versions' do assert_equal(1, PaperTrail::Version.count) end
should 'creation should change the number of versions' do
assert_equal(1, PaperTrail::Version.count)
end
context 'which updates an ignored column' do context 'which updates an ignored column' do
setup { @article.update_attributes :title => 'My first title' } should 'not change the number of versions' do
should 'not change the number of versions' do assert_equal(1, PaperTrail::Version.count) end @article.update_attributes :title => 'My first title'
assert_equal(1, PaperTrail::Version.count)
end
end end
context 'which updates an ignored column with truly Proc' do context 'which updates an ignored column with truly Proc' do
setup { @article.update_attributes :abstract => 'ignore abstract' } should 'not change the number of versions' do
should 'not change the number of versions' do assert_equal(1, PaperTrail::Version.count) end @article.update_attributes :abstract => 'ignore abstract'
assert_equal(1, PaperTrail::Version.count)
end
end end
context 'which updates an ignored column with falsy Proc' do context 'which updates an ignored column with falsy Proc' do
setup { @article.update_attributes :abstract => 'do not ignore abstract!' } should 'change the number of versions' do
should 'change the number of versions' do assert_equal(2, PaperTrail::Version.count) end @article.update_attributes :abstract => 'do not ignore abstract!'
assert_equal(2, PaperTrail::Version.count)
end
end end
context 'which updates an ignored column, ignored with truly Proc and a selected column' do context 'which updates an ignored column, ignored with truly Proc and a selected column' do
setup { @article.update_attributes :title => 'My first title', setup do
@article.update_attributes :title => 'My first title',
:content => 'Some text here.', :content => 'Some text here.',
:abstract => 'ignore abstract' :abstract => 'ignore abstract'
} end
should 'change the number of versions' do assert_equal(2, PaperTrail::Version.count) end
should 'change the number of versions' do
assert_equal(2, PaperTrail::Version.count)
end
should "show the new version in the model's `versions` association" do should "show the new version in the model's `versions` association" do
assert_equal(2, @article.versions.size) assert_equal(2, @article.versions.size)
end end
should 'have stored only non-ignored attributes' do should 'have stored only non-ignored attributes' do
assert_equal ({'content' => [nil, 'Some text here.']}), @article.versions.last.changeset expected = { 'content' => [nil, 'Some text here.'] }
assert_equal expected, @article.versions.last.changeset
end end
end end
context 'which updates an ignored column, ignored with falsy Proc and a selected column' do context 'which updates an ignored column, ignored with falsy Proc and a selected column' do
setup { @article.update_attributes :title => 'My first title', setup do
@article.update_attributes :title => 'My first title',
:content => 'Some text here.', :content => 'Some text here.',
:abstract => 'do not ignore abstract' :abstract => 'do not ignore abstract'
} end
should 'change the number of versions' do assert_equal(2, PaperTrail::Version.count) end
should 'change the number of versions' do
assert_equal(2, PaperTrail::Version.count)
end
should "show the new version in the model's `versions` association" do should "show the new version in the model's `versions` association" do
assert_equal(2, @article.versions.size) assert_equal(2, @article.versions.size)
end end
should 'have stored only non-ignored attributes' do should 'have stored only non-ignored attributes' do
assert_equal ({'content' => [nil, 'Some text here.'], 'abstract' => [nil, 'do not ignore abstract']}), @article.versions.last.changeset expected = {
'content' => [nil, 'Some text here.'],
'abstract' => [nil, 'do not ignore abstract']
}
assert_equal expected, @article.versions.last.changeset
end end
end end
context 'which updates a selected column' do context 'which updates a selected column' do
setup { @article.update_attributes :content => 'Some text here.' } setup { @article.update_attributes :content => 'Some text here.' }
should 'change the number of versions' do assert_equal(2, PaperTrail::Version.count) end should 'change the number of versions' do
assert_equal(2, PaperTrail::Version.count)
end
should "show the new version in the model's `versions` association" do should "show the new version in the model's `versions` association" do
assert_equal(2, @article.versions.size) assert_equal(2, @article.versions.size)
@ -64,30 +88,46 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
end end
context 'which updates a non-ignored and non-selected column' do context 'which updates a non-ignored and non-selected column' do
setup { @article.update_attributes :abstract => 'Other abstract'} should 'not change the number of versions' do
should 'not change the number of versions' do assert_equal(1, PaperTrail::Version.count) end @article.update_attributes :abstract => 'Other abstract'
assert_equal(1, PaperTrail::Version.count)
end
end end
context 'which updates a skipped column' do context 'which updates a skipped column' do
setup { @article.update_attributes :file_upload => 'Your data goes here' } should 'not change the number of versions' do
should 'not change the number of versions' do assert_equal(1, PaperTrail::Version.count) end @article.update_attributes :file_upload => 'Your data goes here'
assert_equal(1, PaperTrail::Version.count)
end
end end
context 'which updates a skipped column and a selected column' do context 'which updates a skipped column and a selected column' do
setup { @article.update_attributes :file_upload => 'Your data goes here', :content => 'Some text here.' } setup do
should 'change the number of versions' do assert_equal(2, PaperTrail::Version.count) end @article.update_attributes(
file_upload: 'Your data goes here',
content: 'Some text here.'
)
end
should 'change the number of versions' do
assert_equal(2, PaperTrail::Version.count)
end
should "show the new version in the model's `versions` association" do should "show the new version in the model's `versions` association" do
assert_equal(2, @article.versions.size) assert_equal(2, @article.versions.size)
end end
should 'have stored only non-skipped attributes' do should 'have stored only non-skipped attributes' do
assert_equal ({'content' => [nil, 'Some text here.']}), @article.versions.last.changeset assert_equal ({'content' => [nil, 'Some text here.']}),
@article.versions.last.changeset
end end
context 'and when updated again' do context 'and when updated again' do
setup do setup do
@article.update_attributes :file_upload => 'More data goes here', :content => 'More text here.' @article.update_attributes(
file_upload: 'More data goes here',
content: 'More text here.'
)
@old_article = @article.versions.last @old_article = @article.versions.last
end end
@ -147,22 +187,30 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
@translation.save @translation.save
end end
should 'not change the number of versions' do assert_equal(0, PaperTrail::Version.count) end should 'not change the number of versions' do
assert_equal(0, PaperTrail::Version.count)
end
context 'after update' do context 'after update' do
setup { @translation.update_attributes :content => 'Content' } setup { @translation.update_attributes :content => 'Content' }
should 'not change the number of versions' do assert_equal(0, PaperTrail::Version.count) end should 'not change the number of versions' do
assert_equal(0, PaperTrail::Version.count)
end
end end
end end
context 'that are not drafts' do context 'that are not drafts' do
setup { @translation.save } setup { @translation.save }
should 'change the number of versions' do assert_equal(1, PaperTrail::Version.count) end should 'change the number of versions' do
assert_equal(1, PaperTrail::Version.count)
end
context 'after update' do context 'after update' do
setup { @translation.update_attributes :content => 'Content' } setup { @translation.update_attributes :content => 'Content' }
should 'change the number of versions' do assert_equal(2, PaperTrail::Version.count) end should 'change the number of versions' do
assert_equal(2, PaperTrail::Version.count)
end
should "show the new version in the model's `versions` association" do should "show the new version in the model's `versions` association" do
assert_equal(2, @translation.versions.size) assert_equal(2, @translation.versions.size)
@ -171,7 +219,9 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
context 'after destroy' do context 'after destroy' do
setup { @translation.destroy } setup { @translation.destroy }
should 'change the number of versions' do assert_equal(2, PaperTrail::Version.count) end should 'change the number of versions' do
assert_equal(2, PaperTrail::Version.count)
end
should "show the new version in the model's `versions` association" do should "show the new version in the model's `versions` association" do
assert_equal(2, @translation.versions.size) assert_equal(2, @translation.versions.size)
@ -270,9 +320,17 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
should 'have stored changes' do should 'have stored changes' do
# Behavior for ActiveRecord 4 is different than ActiveRecord 3; # Behavior for ActiveRecord 4 is different than ActiveRecord 3;
# AR4 includes the `updated_at` column in changes for updates, which is why we reject it from the right side of this assertion. # AR4 includes the `updated_at` column in changes for updates, which
assert_equal ({'name' => ['Henry', 'Harry']}), PaperTrail.serializer.load(@widget.versions.last.object_changes).reject { |k,v| k.to_sym == :updated_at } # is why we reject it from the right side of this assertion.
assert_equal ({'name' => ['Henry', 'Harry']}), @widget.versions.last.changeset.reject { |k,v| k.to_sym == :updated_at } last_obj_changes = @widget.versions.last.object_changes
actual = PaperTrail.serializer.load(last_obj_changes).reject { |k, v|
k.to_sym == :updated_at
}
assert_equal ({'name' => ['Henry', 'Harry']}), actual
actual = @widget.versions.last.changeset.reject { |k, v|
k.to_sym == :updated_at
}
assert_equal ({'name' => ['Henry', 'Harry']}), actual
end end
should 'return changes with indifferent access' do should 'return changes with indifferent access' do
@ -304,14 +362,18 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
should 'not copy the has_one association by default when reifying' do should 'not copy the has_one association by default when reifying' do
reified_widget = @widget.versions.last.reify reified_widget = @widget.versions.last.reify
assert_equal @wotsit, reified_widget.wotsit # association hasn't been affected by reifying # association hasn't been affected by reifying
assert_equal @wotsit, @widget.reload.wotsit # confirm that the association is correct assert_equal @wotsit, reified_widget.wotsit
# confirm that the association is correct
assert_equal @wotsit, @widget.reload.wotsit
end end
should 'copy the has_one association when reifying with :has_one => true' do should 'copy the has_one association when reifying with :has_one => true' do
reified_widget = @widget.versions.last.reify(:has_one => true) reified_widget = @widget.versions.last.reify(:has_one => true)
assert_nil reified_widget.wotsit # wotsit wasn't there at the last version # wotsit wasn't there at the last version
assert_equal @wotsit, @widget.reload.wotsit # wotsit should still exist on live object assert_nil reified_widget.wotsit
# wotsit should still exist on live object
assert_equal @wotsit, @widget.reload.wotsit
end end
end end
@ -677,7 +739,9 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
end end
should 'reify with the correct type' do should 'reify with the correct type' do
# For some reason this test appears to be broken on AR4 in the test env. Executing it manually in the Rails console seems to work.. not sure what the issues is here. # For some reason this test appears to be broken on AR4 in the test env.
# Executing it manually in the Rails console seems to work.. not sure what
# the issues is here.
assert_kind_of FooWidget, @foo.versions.last.reify if ActiveRecord::VERSION::MAJOR < 4 assert_kind_of FooWidget, @foo.versions.last.reify if ActiveRecord::VERSION::MAJOR < 4
assert_equal @foo.versions.first, PaperTrail::Version.last.previous assert_equal @foo.versions.first, PaperTrail::Version.last.previous
assert_nil PaperTrail::Version.last.next assert_nil PaperTrail::Version.last.next
@ -727,19 +791,19 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
assert_equal 'Widget', @widget.version_at(@created).name assert_equal 'Widget', @widget.version_at(@created).name
end end
should "return how it looked when created for version_at just before its first update" do should "return how it looked before its first update" do
assert_equal 'Widget', @widget.version_at(@first_update - 1).name assert_equal 'Widget', @widget.version_at(@first_update - 1).name
end end
should "return how it looked when first updated for version_at its first update" do should "return how it looked after its first update" do
assert_equal 'Fidget', @widget.version_at(@first_update).name assert_equal 'Fidget', @widget.version_at(@first_update).name
end end
should 'return how it looked when first updated for version_at just before its second update' do should 'return how it looked before its second update' do
assert_equal 'Fidget', @widget.version_at(@second_update - 1).name assert_equal 'Fidget', @widget.version_at(@second_update - 1).name
end end
should 'return how it looked when subsequently updated for version_at its second update' do should 'return how it looked after its second update' do
assert_equal 'Digit', @widget.version_at(@second_update).name assert_equal 'Digit', @widget.version_at(@second_update).name
end end
@ -749,7 +813,8 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
context 'passing in a string representation of a timestamp' do context 'passing in a string representation of a timestamp' do
should 'still return a widget when appropriate' do should 'still return a widget when appropriate' do
# need to add 1 second onto the timestamps before casting to a string, since casting a Time to a string drops the microseconds # need to add 1 second onto the timestamps before casting to a string,
# since casting a Time to a string drops the microseconds
assert_equal 'Widget', @widget.version_at((@created + 1.second).to_s).name assert_equal 'Widget', @widget.version_at((@created + 1.second).to_s).name
assert_equal 'Fidget', @widget.version_at((@first_update + 1.second).to_s).name assert_equal 'Fidget', @widget.version_at((@first_update + 1.second).to_s).name
assert_equal 'Digit', @widget.version_at((@second_update + 1.second).to_s).name assert_equal 'Digit', @widget.version_at((@second_update + 1.second).to_s).name
@ -769,10 +834,14 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
end end
should 'return versions in the time period' do should 'return versions in the time period' do
assert_equal ['Fidget'], @widget.versions_between(20.days.ago, 10.days.ago).map(&:name) assert_equal ['Fidget'],
assert_equal ['Widget', 'Fidget'], @widget.versions_between(45.days.ago, 10.days.ago).map(&:name) @widget.versions_between(20.days.ago, 10.days.ago).map(&:name)
assert_equal ['Fidget', 'Digit', 'Digit'], @widget.versions_between(16.days.ago, 1.minute.ago).map(&:name) assert_equal ['Widget', 'Fidget'],
assert_equal [], @widget.versions_between(60.days.ago, 45.days.ago).map(&:name) @widget.versions_between(45.days.ago, 10.days.ago).map(&:name)
assert_equal ['Fidget', 'Digit', 'Digit'],
@widget.versions_between(16.days.ago, 1.minute.ago).map(&:name)
assert_equal [],
@widget.versions_between(60.days.ago, 45.days.ago).map(&:name)
end end
end end
@ -866,19 +935,19 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
context 'and destroyed' do context 'and destroyed' do
setup { @article.destroy } setup { @article.destroy }
should 'store fixed meta data' do should 'store fixed metadata' do
assert_equal 42, @article.versions.last.answer assert_equal 42, @article.versions.last.answer
end end
should 'store dynamic meta data which is independent of the item' do should 'store dynamic metadata which is independent of the item' do
assert_equal '31 + 11 = 42', @article.versions.last.question assert_equal '31 + 11 = 42', @article.versions.last.question
end end
should 'store dynamic meta data which depends on the item' do should 'store dynamic metadata which depends on the item' do
assert_equal @article.id, @article.versions.last.article_id assert_equal @article.id, @article.versions.last.article_id
end end
should 'store dynamic meta data based on an attribute of the item prior to the destruction' do should 'store dynamic metadata based on attribute of item prior to destruction' do
assert_equal @initial_title, @article.versions.last.title assert_equal @initial_title, @article.versions.last.title
end end
end end
@ -967,7 +1036,11 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
count = PaperTrail::Version.count count = PaperTrail::Version.count
@book.authors.create :name => 'Tolstoy' @book.authors.create :name => 'Tolstoy'
assert_equal 2, PaperTrail::Version.count - count assert_equal 2, PaperTrail::Version.count - count
assert_same_elements [Person.last, Authorship.last], [PaperTrail::Version.order(:id).to_a[-2].item, PaperTrail::Version.last.item] actual = [
PaperTrail::Version.order(:id).to_a[-2].item,
PaperTrail::Version.last.item
]
assert_same_elements [Person.last, Authorship.last], actual
end end
should 'store version on join destroy' do should 'store version on join destroy' do
@ -1005,28 +1078,38 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
end end
# Test for serialization: # Test for serialization:
should 'version.object_changes should not have stored the default, ridiculously long (to_yaml) serialization of the TimeZone object' do should 'version.object_changes should store long serialization of TimeZone object' do
assert @person.versions.last.object_changes.length < 105, "object_changes length was #{@person.versions.last.object_changes.length}" len = @person.versions.last.object_changes.length
assert len < 105, "object_changes length was #{len}"
end end
# It should store the serialized value. # It should store the serialized value.
should 'version.object_changes attribute should have stored the value returned by the attribute serializer' do should 'version.object_changes attribute should have stored the value from serializer' do
as_stored_in_version = HashWithIndifferentAccess[YAML::load(@person.versions.last.object_changes)] as_stored_in_version = HashWithIndifferentAccess[
YAML::load(@person.versions.last.object_changes)
]
assert_equal [nil, 'Samoa'], as_stored_in_version[:time_zone] assert_equal [nil, 'Samoa'], as_stored_in_version[:time_zone]
serialized_value = Person::TimeZoneSerializer.dump(@person.time_zone) serialized_value = Person::TimeZoneSerializer.dump(@person.time_zone)
assert_equal serialized_value, as_stored_in_version[:time_zone].last assert_equal serialized_value, as_stored_in_version[:time_zone].last
end end
# Tests for unserialization: # Tests for unserialization:
should 'version.changeset should convert the attribute value back to its original, unserialized value' do should 'version.changeset should convert attribute to original, unserialized value' do
unserialized_value = Person::TimeZoneSerializer.load(@person.time_zone) unserialized_value = Person::TimeZoneSerializer.load(@person.time_zone)
assert_equal unserialized_value, @person.versions.last.changeset[:time_zone].last assert_equal unserialized_value,
@person.versions.last.changeset[:time_zone].last
end end
should "record.changes (before save) returns the original, unserialized values" do should "record.changes (before save) returns the original, unserialized values" do
assert_equal [NilClass, ActiveSupport::TimeZone], @changes_before_save[:time_zone].map(&:class) assert_equal [NilClass, ActiveSupport::TimeZone],
@changes_before_save[:time_zone].map(&:class)
end end
should 'version.changeset should be the same as record.changes was before the save' do should 'version.changeset should be the same as record.changes was before the save' do
assert_equal @changes_before_save, @person.versions.last.changeset.delete_if { |key, val| key.to_sym == :id } actual = @person.versions.last.changeset.delete_if { |key, val| key.to_sym == :id }
assert_equal [NilClass, ActiveSupport::TimeZone], @person.versions.last.changeset[:time_zone].map(&:class) assert_equal @changes_before_save, actual
actual = @person.versions.last.changeset[:time_zone].map(&:class)
assert_equal [NilClass, ActiveSupport::TimeZone], actual
end end
context 'when that attribute is updated' do context 'when that attribute is updated' do
@ -1037,46 +1120,73 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
@person.save! @person.save!
end end
# Tests for serialization: # Tests for serialization
# Before the serialized attributes fix, the object/object_changes value that was stored was ridiculously long (58723). # -----------------------
should 'version.object should not have stored the default, ridiculously long (to_yaml) serialization of the TimeZone object' do #
assert @person.versions.last.object.length < 105, "object length was #{@person.versions.last.object.length}" # Before the serialized attributes fix, the object/object_changes value
# that was stored was ridiculously long (58723).
#
# version.object should not have stored the default, ridiculously long
# (to_yaml) serialization of the TimeZone object.
should "object should not store long serialization of TimeZone object" do
len = @person.versions.last.object.length
assert len < 105, "object length was #{len}"
end end
# Need an additional clause to detect what version of ActiveRecord is being used for this test because AR4 injects the `updated_at` column into the changeset for updates to models
should 'version.object_changes should not have stored the default, ridiculously long (to_yaml) serialization of the TimeZone object' do # Need an additional clause to detect what version of ActiveRecord is
assert @person.versions.last.object_changes.length < (ActiveRecord::VERSION::MAJOR < 4 ? 105 : 118), "object_changes length was #{@person.versions.last.object_changes.length}" # being used for this test because AR4 injects the `updated_at` column
# into the changeset for updates to models.
#
# version.object_changes should not have stored the default,
# ridiculously long (to_yaml) serialization of the TimeZone object
should "object_changes should not store long serialization of TimeZone object" do
max_len = ActiveRecord::VERSION::MAJOR < 4 ? 105 : 118
len = @person.versions.last.object_changes.length
assert len < max_len, "object_changes length was #{len}"
end end
# But now it stores the short, serialized value. # But now it stores the short, serialized value.
should 'version.object attribute should have stored the value returned by the attribute serializer' do should 'version.object attribute should have stored value from serializer' do
as_stored_in_version = HashWithIndifferentAccess[YAML::load(@person.versions.last.object)] as_stored_in_version = HashWithIndifferentAccess[
YAML::load(@person.versions.last.object)
]
assert_equal 'Samoa', as_stored_in_version[:time_zone] assert_equal 'Samoa', as_stored_in_version[:time_zone]
serialized_value = Person::TimeZoneSerializer.dump(@attribute_value_before_change) serialized_value = Person::TimeZoneSerializer.dump(@attribute_value_before_change)
assert_equal serialized_value, as_stored_in_version[:time_zone] assert_equal serialized_value, as_stored_in_version[:time_zone]
end end
should 'version.object_changes attribute should have stored the value returned by the attribute serializer' do
as_stored_in_version = HashWithIndifferentAccess[YAML::load(@person.versions.last.object_changes)] should 'version.object_changes attribute should have stored value from serializer' do
as_stored_in_version = HashWithIndifferentAccess[
YAML::load(@person.versions.last.object_changes)
]
assert_equal ['Samoa', 'Pacific Time (US & Canada)'], as_stored_in_version[:time_zone] assert_equal ['Samoa', 'Pacific Time (US & Canada)'], as_stored_in_version[:time_zone]
serialized_value = Person::TimeZoneSerializer.dump(@person.time_zone) serialized_value = Person::TimeZoneSerializer.dump(@person.time_zone)
assert_equal serialized_value, as_stored_in_version[:time_zone].last assert_equal serialized_value, as_stored_in_version[:time_zone].last
end end
# Tests for unserialization: # Tests for unserialization:
should 'version.reify should convert the attribute value back to its original, unserialized value' do should 'version.reify should convert attribute to original, unserialized value' do
unserialized_value = Person::TimeZoneSerializer.load(@attribute_value_before_change) unserialized_value = Person::TimeZoneSerializer.load(@attribute_value_before_change)
assert_equal unserialized_value, @person.versions.last.reify.time_zone assert_equal unserialized_value,
end @person.versions.last.reify.time_zone
should 'version.changeset should convert the attribute value back to its original, unserialized value' do
unserialized_value = Person::TimeZoneSerializer.load(@person.time_zone)
assert_equal unserialized_value, @person.versions.last.changeset[:time_zone].last
end
should "record.changes (before save) returns the original, unserialized values" do
assert_equal [ActiveSupport::TimeZone, ActiveSupport::TimeZone], @changes_before_save[:time_zone].map(&:class)
end
should 'version.changeset should be the same as record.changes was before the save' do
assert_equal @changes_before_save, @person.versions.last.changeset
assert_equal [ActiveSupport::TimeZone, ActiveSupport::TimeZone], @person.versions.last.changeset[:time_zone].map(&:class)
end end
should 'version.changeset should convert attribute to original, unserialized value' do
unserialized_value = Person::TimeZoneSerializer.load(@person.time_zone)
assert_equal unserialized_value,
@person.versions.last.changeset[:time_zone].last
end
should "record.changes (before save) returns the original, unserialized values" do
assert_equal [ActiveSupport::TimeZone, ActiveSupport::TimeZone],
@changes_before_save[:time_zone].map(&:class)
end
should 'version.changeset should be the same as record.changes was before the save' do
assert_equal @changes_before_save, @person.versions.last.changeset
assert_equal [ActiveSupport::TimeZone, ActiveSupport::TimeZone],
@person.versions.last.changeset[:time_zone].map(&:class)
end
end end
end end
end end

View File

@ -3,12 +3,17 @@ require 'test_helper'
class ProtectedAttrsTest < ActiveSupport::TestCase class ProtectedAttrsTest < ActiveSupport::TestCase
subject { ProtectedWidget.new } subject { ProtectedWidget.new }
if ActiveRecord::VERSION::MAJOR < 4 # these ActiveModel matchers (provided by shoulda-matchers) only work for Rails 3 # These ActiveModel matchers (provided by shoulda-matchers) only work for
# Rails 3.
if ActiveRecord::VERSION::MAJOR < 4
accessible_attrs = ProtectedWidget.accessible_attributes.to_a accessible_attrs = ProtectedWidget.accessible_attributes.to_a
accessible_attrs.each do |attr_name| accessible_attrs.each do |attr_name|
should allow_mass_assignment_of(attr_name.to_sym) should allow_mass_assignment_of(attr_name.to_sym)
end end
ProtectedWidget.column_names.reject { |column_name| accessible_attrs.include?(column_name) }.each do |attr_name| inaccessible = ProtectedWidget.
column_names.
reject { |column_name| accessible_attrs.include?(column_name) }
inaccessible.each do |attr_name|
should_not allow_mass_assignment_of(attr_name.to_sym) should_not allow_mass_assignment_of(attr_name.to_sym)
end end
end end

View File

@ -10,7 +10,10 @@ class SerializerTest < ActiveSupport::TestCase
END END
@fluxor = Fluxor.create :name => 'Some text.' @fluxor = Fluxor.create :name => 'Some text.'
@original_fluxor_attributes = @fluxor.send(:attributes_before_change) # this is exactly what PaperTrail serializes
# this is exactly what PaperTrail serializes
@original_fluxor_attributes = @fluxor.send(:attributes_before_change)
@fluxor.update_attributes :name => 'Some more text.' @fluxor.update_attributes :name => 'Some more text.'
end end
@ -37,7 +40,10 @@ class SerializerTest < ActiveSupport::TestCase
END END
@fluxor = Fluxor.create :name => 'Some text.' @fluxor = Fluxor.create :name => 'Some text.'
@original_fluxor_attributes = @fluxor.send(:attributes_before_change) # this is exactly what PaperTrail serializes
# this is exactly what PaperTrail serializes
@original_fluxor_attributes = @fluxor.send(:attributes_before_change)
@fluxor.update_attributes :name => 'Some more text.' @fluxor.update_attributes :name => 'Some more text.'
end end
@ -52,8 +58,10 @@ class SerializerTest < ActiveSupport::TestCase
assert_equal 'Some text.', @fluxor.versions[1].reify.name assert_equal 'Some text.', @fluxor.versions[1].reify.name
# Check values are stored as JSON. # Check values are stored as JSON.
assert_equal @original_fluxor_attributes, ActiveSupport::JSON.decode(@fluxor.versions[1].object) assert_equal @original_fluxor_attributes,
assert_equal ActiveSupport::JSON.encode(@original_fluxor_attributes), @fluxor.versions[1].object ActiveSupport::JSON.decode(@fluxor.versions[1].object)
assert_equal ActiveSupport::JSON.encode(@original_fluxor_attributes),
@fluxor.versions[1].object
end end
should 'store object_changes' do should 'store object_changes' do
@ -75,7 +83,12 @@ class SerializerTest < ActiveSupport::TestCase
END END
@fluxor = Fluxor.create @fluxor = Fluxor.create
@original_fluxor_attributes = @fluxor.send(:attributes_before_change).reject { |k,v| v.nil? } # this is exactly what PaperTrail serializes
# this is exactly what PaperTrail serializes
@original_fluxor_attributes = @fluxor.
send(:attributes_before_change).
reject { |_k, v| v.nil? }
@fluxor.update_attributes :name => 'Some more text.' @fluxor.update_attributes :name => 'Some more text.'
end end
@ -90,8 +103,10 @@ class SerializerTest < ActiveSupport::TestCase
assert_nil @fluxor.versions[1].reify.name assert_nil @fluxor.versions[1].reify.name
# Check values are stored as JSON. # Check values are stored as JSON.
assert_equal @original_fluxor_attributes, ActiveSupport::JSON.decode(@fluxor.versions[1].object) assert_equal @original_fluxor_attributes,
assert_equal ActiveSupport::JSON.encode(@original_fluxor_attributes), @fluxor.versions[1].object ActiveSupport::JSON.decode(@fluxor.versions[1].object)
assert_equal ActiveSupport::JSON.encode(@original_fluxor_attributes),
@fluxor.versions[1].object
end end
should 'store object_changes' do should 'store object_changes' do

View File

@ -20,7 +20,8 @@ class MixinJsonTest < ActiveSupport::TestCase
end end
should '`deserialize` JSON to Ruby, removing pairs with `blank` keys or values' do should '`deserialize` JSON to Ruby, removing pairs with `blank` keys or values' do
assert_equal @hash.reject { |k,v| k.blank? || v.blank? }, CustomJsonSerializer.load(@hash_as_json) assert_equal @hash.reject { |k,v| k.blank? || v.blank? },
CustomJsonSerializer.load(@hash_as_json)
end end
end end
@ -30,7 +31,8 @@ class MixinJsonTest < ActiveSupport::TestCase
end end
should '`serialize` Ruby to JSON, removing pairs with `nil` values' do should '`serialize` Ruby to JSON, removing pairs with `nil` values' do
assert_equal @hash.reject { |k,v| v.nil? }.to_json, CustomJsonSerializer.dump(@hash) assert_equal @hash.reject { |k,v| v.nil? }.to_json,
CustomJsonSerializer.dump(@hash)
end end
end end
end end

View File

@ -5,7 +5,11 @@ module CustomYamlSerializer
def self.load(string) def self.load(string)
parsed_value = super(string) parsed_value = super(string)
parsed_value.is_a?(Hash) ? parsed_value.reject { |k,v| k.blank? || v.blank? } : parsed_value if parsed_value.is_a?(Hash)
parsed_value.reject { |k, v| k.blank? || v.blank? }
else
parsed_value
end
end end
def self.dump(object) def self.dump(object)
@ -32,7 +36,8 @@ class MixinYamlTest < ActiveSupport::TestCase
end end
should '`deserialize` YAML to Ruby, removing pairs with `blank` keys or values' do should '`deserialize` YAML to Ruby, removing pairs with `blank` keys or values' do
assert_equal @hash.reject { |k,v| k.blank? || v.blank? }, CustomYamlSerializer.load(@hash_as_yaml) assert_equal @hash.reject { |k,v| k.blank? || v.blank? },
CustomYamlSerializer.load(@hash_as_yaml)
end end
end end
@ -42,7 +47,8 @@ class MixinYamlTest < ActiveSupport::TestCase
end end
should '`serialize` Ruby to YAML, removing pairs with `nil` values' do should '`serialize` Ruby to YAML, removing pairs with `nil` values' do
assert_equal @hash.reject { |k,v| v.nil? }.to_yaml, CustomYamlSerializer.dump(@hash) assert_equal @hash.reject { |k,v| v.nil? }.to_yaml,
CustomYamlSerializer.dump(@hash)
end end
end end