Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Migrated code from the older big_brother project.

  • Loading branch information...
commit 425c68d8edaaa289324690cc9e5e5199d09e58a2 0 parents
@kunklejr authored
3  .gitignore
@@ -0,0 +1,3 @@
+coverage
+rdoc
+auditor-*.gem
20 LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2009 Near Infinity Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
69 README.rdoc
@@ -0,0 +1,69 @@
+= Auditor
+
+Auditor is a Rails 3 plugin for auditing access to your ActiveRecord model objects. It allows you to declaratively specify what CRUD operations should be audited and store that audit data in the database. You can also specify what attributes of model objects should automatically be audited and which ones should be ignored.
+
+To audit your model objects you must specify which operations should be audited and which model attributes should be tracked. This "specify what you want to collect" approach avoids being overwhelmed with data and makes you carefully consider what is most important to audit.
+
+= Installation
+
+To use it with your Rails 3 project, add the following line to your Gemfile
+
+ gem 'auditor'
+
+Auditor can also be installed as a Rails plugin
+
+ rails plugin install git://github.com/nearinfinity/auditor.git
+
+Generate the migration and create the audits table
+
+ rails generate auditor:migration
+ rake db:migrate
+
+= Setup
+
+Auditor needs to know who the current user is, but with no standard for doing so you'll have to do a little work to set things up. You simply need to set your current user model object as the Auditor current user before any CRUD operations are performed. For example, in a Rails application you could add the following to your application_controller.rb
+
+ class ApplicationController < ActionController::Base
+ before_filter :set_current_user
+
+ private
+
+ def set_current_user
+ Auditor::User.current_user = @current_user
+ end
+ end
+
+= Examples
+
+Auditor works very similarly to Joshua Clayton's acts_as_auditable plugin. There are two audit calls in the example below. The first declares that create and update actions should be audited for the EditablePage model and the string returned by the passed block should be included as a custom message. The second audit call simply changes the custom message when auditing destroy (aka delete) actions.
+
+ class EditablePage < ActiveRecord::Base
+ include Auditor::ModelAudit
+
+ has_many :tags
+
+ audit(:create, :update) { |model, user| "Editable page modified by #{user.display_name}" }
+ audit(:destroy) { |model, user| "#{user.display_name} deleted editable page #{model.id}" }
+ end
+
+All audit data is stored in a table named Audits, which is automatically created for you when you run the migration included with the plugin. However, there's a lot more recorded than just the custom message, including:
+
+* auditable_id - the primary key of the table belonging to the audited model object
+* auditable_type - the class type of the audited model object
+* auditable_version - the version number of the audited model object (if versioning is tracked)
+* user_id - the primary key of the table belonging to the user being audited
+* user_type - the class type of the model object representing users in your application
+* action - a string indicating the action that was audited (create, update, destroy, or find)
+* message - the custom message returned by any block passed to the audit call
+* edits - a YAML string containing the before and after state of any model attributes that changed
+* created_at - the date and time the audit record was recorded
+
+The edits column automatically serializes the before and after state of any model attributes that change during the action. If there are only a few attributes you want to audit or a couple that you want to prevent from being audited, you can specify that in the audit call. For example
+
+ # Prevent SSN and passwords from being saved in the audit table
+ audit(:create, :destroy, :except => [:ssn, :password])
+
+ # Only audit edits to the title column when destroying/deleting
+ audit(:destroy, :only => :title)
+
+Copyright (c) 2010 Near Infinity Corporation, released under the MIT license
37 Rakefile
@@ -0,0 +1,37 @@
+$:.unshift File.expand_path("../lib", __FILE__)
+
+require 'rake'
+require 'rake/rdoctask'
+require 'rspec/core/rake_task'
+
+desc 'Default: run specs'
+task :default => :spec
+
+desc "Run specs"
+RSpec::Core::RakeTask.new do |t|
+ t.rspec_opts = %w(-fs --color)
+end
+
+desc "Run specs with RCov"
+RSpec::Core::RakeTask.new(:rcov) do |t|
+ t.rspec_opts = %w(-fs --color)
+ t.rcov = true
+ t.rcov_opts = %w(--exclude "spec/*,gems/*")
+end
+
+desc 'Generate documentation for the gem.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'Auditor'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+task :build do
+ system "gem build auditor.gemspec"
+end
+
+task :release => :build do
+ system "gem push auditor-#{Auditor::VERSION}"
+end
24 auditor.gemspec
@@ -0,0 +1,24 @@
+# -*- encoding: utf-8 -*-
+lib = File.expand_path('../lib/', __FILE__)
+$:.unshift lib unless $:.include?(lib)
+
+require 'auditor/version'
+
+Gem::Specification.new do |s|
+ s.name = "auditor"
+ s.version = Auditor::VERSION
+ s.platform = Gem::Platform::RUBY
+ s.authors = ["Jeff Kunkle", "Matt Wizeman"]
+ s.homepage = "http://github.com/nearinfinity/auditor"
+ s.summary = "Rails 3 plugin for auditing access to your ActiveRecord model objects"
+ s.description = "Auditor allows you to declaratively specify what CRUD operations should be audited and save the audit data to the database."
+ s.license = "MIT"
+
+ s.required_rubygems_version = ">= 1.3.6"
+
+ s.add_development_dependency "rspec"
+
+ s.files = Dir.glob("{lib}/**/*") + %w(LICENSE README.rdoc)
+ s.test_files = Dir.glob("{spec}/**/*")
+ s.require_path = 'lib'
+end
1  init.rb
@@ -0,0 +1 @@
+require 'auditor'
9 lib/auditor.rb
@@ -0,0 +1,9 @@
+require 'auditor/audit'
+require 'auditor/integration'
+require 'auditor/model_audit'
+require 'auditor/user'
+require 'auditor/version'
+
+module Auditor
+ class Error < StandardError; end
+end
6 lib/auditor/audit.rb
@@ -0,0 +1,6 @@
+require 'active_record'
+
+class Audit < ActiveRecord::Base
+ validates_presence_of :auditable_id, :auditable_type, :user_id, :user_type, :action
+ serialize :edits
+end
36 lib/auditor/config_parser.rb
@@ -0,0 +1,36 @@
+module Auditor
+ class ConfigParser
+
+ def self.extract_config(args)
+ options = (args.delete_at(args.size - 1) if args.last.kind_of?(Hash)) || {}
+ normalize_config args, options
+ validate_config args, options
+ options = normalize_options(options)
+
+ [args, options]
+ end
+
+ private
+
+ def self.normalize_config(actions, options)
+ actions.each_with_index { |item, index| actions[index] = item.to_sym }
+ options.each_pair { |k, v| options[k.to_sym] = options.delete(k) unless k.kind_of? Symbol }
+ end
+
+ def self.normalize_options(options)
+ return { :except => [], :only => [] } if options.nil? || options.empty?
+ options[:except] = options[:except] || []
+ options[:only] = options[:only] || []
+ options[:except] = Array(options[:except]).map(&:to_s)
+ options[:only] = Array(options[:only]).map(&:to_s)
+ options
+ end
+
+ def self.validate_config(actions, options)
+ raise Auditor::Error.new "at least one :create, :find, :update, or :destroy action must be specified" if actions.empty?
+ raise Auditor::Error.new ":create, :find, :update, and :destroy are the only valid actions" unless actions.all? { |a| [:create, :find, :update, :destroy].include? a }
+ raise Auditor::Error.new "only one of :except and :only can be specified" if options.size > 1
+ end
+
+ end
+end
49 lib/auditor/integration.rb
@@ -0,0 +1,49 @@
+require 'auditor/thread_status'
+
+module Auditor
+ module Integration
+
+ def without_auditor
+ previously_disabled = auditor_disabled?
+ disable_auditor
+
+ begin
+ result = yield if block_given?
+ ensure
+ enable_auditor unless previously_disabled
+ end
+
+ result
+ end
+
+ def with_auditor
+ previously_disabled = auditor_disabled?
+ enable_auditor
+
+ begin
+ result = yield if block_given?
+ ensure
+ disable_auditor if previously_disabled
+ end
+
+ result
+ end
+
+ def disable_auditor
+ Auditor::ThreadStatus.disable
+ end
+
+ def enable_auditor
+ Auditor::ThreadStatus.enable
+ end
+
+ def auditor_disabled?
+ Auditor::ThreadStatus.disabled?
+ end
+
+ def auditor_enabled?
+ Auditor::ThreadStatus.enabled?
+ end
+
+ end
+end
47 lib/auditor/model_audit.rb
@@ -0,0 +1,47 @@
+require 'auditor/thread_status'
+require 'auditor/config_parser'
+require 'auditor/recorder'
+
+module Auditor
+ module ModelAudit
+
+ def self.included(base)
+ base.extend ClassMethods
+ end
+
+ # ActiveRecord won't call the after_find handler unless it see's a specific after_find method defined
+ def after_find; end
+
+ def auditor_disabled?
+ Auditor::ThreadStatus.disabled? || @auditor_disabled
+ end
+
+ module ClassMethods
+ def audit(*args, &blk)
+ actions, options = Auditor::ConfigParser.extract_config(args)
+
+ actions.each do |action|
+ unless action.to_sym == :find
+ callback = "auditor_before_#{action}"
+ define_method(callback) do
+ @auditor_auditor = Auditor::Recorder.new(action, self, options, &blk)
+ @auditor_auditor.audit_before unless auditor_disabled?
+ true
+ end
+ send "before_#{action}".to_sym, callback
+ end
+
+ callback = "auditor_after_#{action}"
+ define_method(callback) do
+ @auditor_auditor = Auditor::Recorder.new(action, self, options, &blk) if action.to_sym == :find
+ @auditor_auditor.audit_after unless auditor_disabled?
+ true
+ end
+ send "after_#{action}".to_sym, callback
+
+ end
+ end
+ end
+
+ end
+end
44 lib/auditor/recorder.rb
@@ -0,0 +1,44 @@
+require 'auditor/user'
+
+module Auditor
+ class Recorder
+
+ def initialize(action, model, options, &blk)
+ @action, @model, @options, @blk = action.to_sym, model, options, blk
+ end
+
+ def audit_before
+ @audit = Audit.new(:edits => prepare_edits(@model.changes, @options))
+ end
+
+ def audit_after
+ @audit ||= Audit.new
+
+ @audit.attributes = {
+ :auditable_id => @model.id,
+ :auditable_type => @model.class.to_s,
+ :user_id => user.id,
+ :user_type => user.class.to_s,
+ :action => @action.to_s
+ }
+
+ @audit.auditable_version = @model.version if @model.respond_to? :version
+ @audit.message = @blk.call(@model, user) if @blk
+
+ @audit.save
+ end
+
+ private
+ def user
+ Auditor::User.current_user
+ end
+
+ def prepare_edits(changes, options)
+ chg = changes.dup
+ chg = chg.delete_if { |key, value| options[:except].include? key } unless options[:except].empty?
+ chg = chg.delete_if { |key, value| !options[:only].include? key } unless options[:only].empty?
+ chg.empty? ? nil : chg
+ end
+
+ end
+end
20 lib/auditor/spec_helpers.rb
@@ -0,0 +1,20 @@
+module Auditor
+ module SpecHelpers
+ include Auditor::Integration
+
+ def self.included(base)
+ base.class_eval do
+ before(:each) do
+ disable_auditor
+ end
+
+ after(:each) do
+ enable_auditor
+ end
+ end
+ end
+
+ end
+end
+
+
18 lib/auditor/thread_local.rb
@@ -0,0 +1,18 @@
+module Auditor
+ class ThreadLocal
+
+ def initialize(initial_value)
+ @thread_symbol = "#{rand}#{Time.now.to_f}"
+ set initial_value
+ end
+
+ def set(value)
+ Thread.current[@thread_symbol] = value
+ end
+
+ def get
+ Thread.current[@thread_symbol]
+ end
+
+ end
+end
34 lib/auditor/thread_status.rb
@@ -0,0 +1,34 @@
+require 'auditor/thread_local'
+
+module Auditor
+ module ThreadStatus
+
+ def self.enabled?
+ status
+ end
+
+ def self.disabled?
+ !status
+ end
+
+ def self.enable
+ set_status true
+ end
+
+ def self.disable
+ set_status false
+ end
+
+ private
+ def self.status
+ @status = Auditor::ThreadLocal.new(true) if @status.nil?
+ @status.get
+ end
+
+ def self.set_status(status)
+ @status = Auditor::ThreadLocal.new(true) if @status.nil?
+ @status.set status
+ end
+
+ end
+end
16 lib/auditor/user.rb
@@ -0,0 +1,16 @@
+module Auditor
+ module User
+ def current_user
+ Thread.current[@@current_user_symbol]
+ end
+
+ def current_user=(user)
+ Thread.current[@@current_user_symbol] = user
+ end
+
+ module_function :current_user, :current_user=
+
+ private
+ @@current_user_symbol = :auditor_current_user
+ end
+end
3  lib/auditor/version.rb
@@ -0,0 +1,3 @@
+module Auditor
+ VERSION = "1.0.0"
+end
9 lib/generators/auditor.rb
@@ -0,0 +1,9 @@
+module Auditor
+ module Generators
+ class Base < Rails::Generators::NamedBase
+ def self.source_root
+ File.expand_path(File.join(File.dirname(__FILE__), 'auditor', generator_name, 'templates'))
+ end
+ end
+ end
+end
26 lib/generators/auditor/migration/migration_generator.rb
@@ -0,0 +1,26 @@
+require 'rails/generators'
+require 'rails/generators/migration'
+
+module Auditor
+ module Generators
+ class MigrationGenerator < Rails::Generators::Base
+ include Rails::Generators::Migration
+
+ desc "Create migration for Auditor audits table"
+
+ source_root File.expand_path("../templates", __FILE__)
+
+ def self.next_migration_number(dirname)
+ if ActiveRecord::Base.timestamped_migrations
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
+ else
+ "%.3d" % (current_migration_number(dirname) + 1)
+ end
+ end
+
+ def create_migration_file
+ migration_template 'migration.rb', 'db/migrate/create_audits_table.rb'
+ end
+ end
+ end
+end
19 lib/generators/auditor/migration/templates/migration.rb
@@ -0,0 +1,19 @@
+class CreateAuditsTable < ActiveRecord::Migration
+ def self.up
+ create_table :audits, :force => true do |t|
+ t.column :auditable_id, :integer, :null => false
+ t.column :auditable_type, :string, :null => false
+ t.column :auditable_version, :integer
+ t.column :user_id, :integer, :null => false
+ t.column :user_type, :string, :null => false
+ t.column :action, :string, :null => false
+ t.column :message, :text
+ t.column :edits, :text
+ t.column :created_at, :datetime, :null => false
+ end
+ end
+
+ def self.down
+ drop_table :audits
+ end
+end
53 spec/config_parser_spec.rb
@@ -0,0 +1,53 @@
+require File.dirname(__FILE__) + '/spec_helper'
+require 'auditor'
+
+describe Auditor::ConfigParser do
+
+ describe 'Configuration' do
+ it "should parse actions and options from a config array" do
+ config = Auditor::ConfigParser.extract_config([:create, 'update', {:only => :username}])
+ config.should_not be_nil
+ config.should have(2).items
+ config[0].should =~ [:create, :update]
+ config[1].should == {:only => ["username"], :except => []}
+ end
+
+ it "should parse actions and options from a config array when options are absent" do
+ config = Auditor::ConfigParser.extract_config([:create, 'update'])
+ config.should_not be_nil
+ config.should have(2).items
+ config[0].should =~ [:create, :update]
+ config[1].should == {:only => [], :except => []}
+ end
+
+ it "should parse actions" do
+ config = Auditor::ConfigParser.extract_config([:create])
+ config.should_not be_nil
+ config.should have(2).items
+ config[0].should =~ [:create]
+ config[1].should == {:only => [], :except => []}
+ end
+
+ end
+
+ describe 'Configuration Validation' do
+ it "should raise a Auditor::Error if no action is specified" do
+ lambda {
+ Auditor::ConfigParser.instance_eval { validate_config([], {}) }
+ }.should raise_error(Auditor::Error)
+ end
+
+ it "should raise a Auditor::Error if an invalid action is specified" do
+ lambda {
+ Auditor::ConfigParser.instance_eval { validate_config([:create, :udate], {}) }
+ }.should raise_error(Auditor::Error)
+ end
+
+ it "should raise a Auditor::Error if both the except and only options are specified" do
+ lambda {
+ Auditor::ConfigParser.instance_eval { validate_config([:find], {:except => :ssn, :only => :username}) }
+ }.should raise_error(Auditor::Error)
+ end
+ end
+
+end
83 spec/model_audit_spec.rb
@@ -0,0 +1,83 @@
+require File.dirname(__FILE__) + '/spec_helper'
+require 'auditor'
+
+describe Auditor::ModelAudit do
+
+ before(:each) do
+ Auditor::User.current_user = (Class.new do
+ def id; 1 end
+ end).new
+ end
+
+ it 'should audit find' do
+ c = new_model_class.instance_eval { audit(:find); self }
+ verify_standard_audits(c.new, :find)
+ end
+
+ it 'should audit create' do
+ c = new_model_class.instance_eval { audit(:create); self }
+ verify_standard_audits(c.new, :create)
+ end
+
+ it 'should audit update' do
+ c = new_model_class.instance_eval { audit(:update); self }
+ verify_standard_audits(c.new, :update)
+ end
+
+ it 'should audit destroy' do
+ c = new_model_class.instance_eval { audit(:destroy); self }
+ verify_standard_audits(c.new, :destroy)
+ end
+
+ it 'should allow multiple actions to be specified with one audit statment' do
+ c = new_model_class.instance_eval { audit(:create, :update); self }
+ verify_standard_audits(c.new, :create, :update)
+
+ c = new_model_class.instance_eval { audit(:create, :update, :destroy); self }
+ verify_standard_audits(c.new, :create, :update, :destroy)
+
+ c = new_model_class.instance_eval { audit(:create, :update, :destroy, :find); self }
+ verify_standard_audits(c.new, :create, :update, :destroy, :find)
+ end
+
+ def verify_standard_audits(instance, *audited_callbacks)
+ audited_callbacks.each do |action|
+ mock_auditor = mock('auditor')
+ Auditor::Recorder.should_receive(:new).and_return(mock_auditor)
+ mock_auditor.should_receive(:audit_before) unless action == :find
+ mock_auditor.should_receive(:audit_after)
+ instance.send action
+ end
+ end
+
+ def new_model_class
+ Class.new(ActiveRecordMock) do
+ include Auditor::ModelAudit
+ end
+ end
+
+ class ActiveRecordMock
+ def id; 1 end
+
+ [:create, :update, :destroy, :find].each do |action|
+ define_method(action) do
+ send "before_#{action}".to_sym unless action == :find
+ send "after_#{action}".to_sym
+ end
+
+ metaclass = class << self; self end
+ metaclass.instance_eval do
+ unless action == :find
+ define_method("before_#{action}") do |method|
+ define_method("before_#{action}") { send method }
+ end
+ end
+ define_method("after_#{action}") do |method|
+ define_method("after_#{action}") { send method }
+ end
+ end
+ end
+
+ end
+
+end
120 spec/recorder_spec.rb
@@ -0,0 +1,120 @@
+require File.dirname(__FILE__) + '/spec_helper'
+require 'auditor'
+
+describe Auditor::Recorder do
+ before(:each) do
+ @user = Auditor::User.current_user = new_model(7)
+ end
+
+ it 'should create and save a new audit record' do
+ model = new_model(42, {'first_name' => ['old','new']})
+
+ auditor = Auditor::Recorder.new(:create, model, {:except => [], :only => []}) { |m, u| "Model: #{m.id} User: #{u.id}" }
+
+ audit = do_callbacks(auditor, model)
+
+ audit.saved.should be_true
+ audit.action.should == 'create'
+ audit.edits.to_a.should =~ [['first_name', ['old', 'new']]]
+ audit.auditable_id.should == 42
+ audit.auditable_type.should == model.class.to_s
+ audit.user_id.should == @user.id
+ audit.user_type.should == @user.class.to_s
+ audit.auditable_version.should be_nil
+ audit.message.should == 'Model: 42 User: 7'
+ end
+
+ it 'should capture the new id of a created record' do
+ model = new_model
+
+ auditor = Auditor::Recorder.new(:create, model, {:except => [], :only => []})
+
+ audit = do_callbacks(auditor, model)
+
+ audit.saved.should be_true
+ audit.auditable_id.should == 42
+ audit.auditable_type.should == model.class.to_s
+ end
+
+ it 'should set message details to nil if they are not given' do
+ model = new_model
+ auditor = Auditor::Recorder.new(:create, model, {:except => [], :only => []})
+
+ audit = do_callbacks(auditor, model)
+
+ audit.saved.should be_true
+ audit.message.should be_nil
+ end
+
+ it 'should not save change details for excepted attributes' do
+ model = new_model(42, {'first_name' => ['old','new'], 'last_name' => ['old','new']})
+
+ auditor = Auditor::Recorder.new(:create, model, {:except => ['last_name'], :only => []})
+
+ audit = do_callbacks(auditor, model)
+
+ audit.saved.should be_true
+ audit.edits.to_a.should =~ [['first_name', ['old', 'new']]]
+ end
+
+ it 'should only save change details for onlyed attributes' do
+ model = new_model(42, {'first_name' => ['old','new'], 'last_name' => ['old','new']})
+
+ auditor = Auditor::Recorder.new(:create, model, {:except => [], :only => ['last_name']})
+
+ audit = do_callbacks(auditor, model)
+
+ audit.saved.should be_true
+ audit.edits.to_a.should =~ [['last_name', ['old', 'new']]]
+ end
+
+ it 'should not save attributes listed in both the only and except options' do
+ model = new_model(42, {'first_name' => ['old','new'], 'last_name' => ['old','new']})
+
+ auditor = Auditor::Recorder.new(:create, model, {:except => ['last_name'], :only => ['last_name']})
+
+ audit = do_callbacks(auditor, model)
+
+ audit.saved.should be_true
+ audit.edits.should be_nil
+ end
+
+ def do_callbacks(auditor, model)
+ auditor.audit_before
+ audit = auditor.instance_variable_get(:@audit)
+ audit.saved.should be_false
+
+ model.changes = nil
+ model.id = 42 if model.id.nil?
+
+ auditor.audit_after
+ auditor.instance_variable_get(:@audit)
+ end
+
+ def new_model(id = nil, changes = {})
+ model = (Class.new do; attr_accessor :id, :changes; end).new
+ model.id, model.changes = id, changes
+ model
+ end
+
+ class Audit
+ attr_accessor :edits, :saved
+ attr_accessor :action, :auditable_id, :auditable_type, :user_id, :user_type, :auditable_version, :message
+
+ def initialize(attrs={})
+ @edits = attrs.delete(:edits)
+ @saved = false
+ raise "You can only set the edits field in this class" unless attrs.empty?
+ end
+
+ def attributes=(attrs={})
+ attrs.each_pair do |key, val|
+ self.send("#{key}=".to_sym, val)
+ end
+ end
+
+ def save
+ @saved = true
+ end
+ end
+end
45 spec/spec_helper.rb
@@ -0,0 +1,45 @@
+require 'rspec'
+
+# Requires supporting files with custom matchers and macros, etc,
+# in ./support/ and its subdirectories.
+Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
+
+RSpec.configure do |config|
+ # If you're not using ActiveRecord you should remove these
+ # lines, delete config/database.yml and disable :active_record
+ # in your config/boot.rb
+ # config.use_transactional_fixtures = true
+ # config.use_instantiated_fixtures = false
+
+ # == Fixtures
+ #
+ # You can declare fixtures for each example_group like this:
+ # describe "...." do
+ # fixtures :table_a, :table_b
+ #
+ # Alternatively, if you prefer to declare them only once, you can
+ # do so right here. Just uncomment the next line and replace the fixture
+ # names with your fixtures.
+ #
+ # config.global_fixtures = :all
+ #
+ # If you declare global fixtures, be aware that they will be declared
+ # for all of your examples, even those that don't use them.
+ #
+ # You can also declare which fixtures to use (for example fixtures for test/fixtures):
+ #
+ # config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
+ #
+ # == Mock Framework
+ #
+ # RSpec uses it's own mocking framework by default. If you prefer to
+ # use mocha, flexmock or RR, uncomment the appropriate line:
+ #
+ # config.mock_with :mocha
+ # config.mock_with :flexmock
+ # config.mock_with :rr
+ #
+ # == Notes
+ #
+ # For more information take a look at Spec::Runner::Configuration and Spec::Runner
+end
29 spec/support/auditor_helpers.rb
@@ -0,0 +1,29 @@
+module AuditorHelpers
+
+ def current_user=(user)
+ Auditor::User.current_user = user
+ end
+
+ def current_user
+ Auditor::User.current_user
+ end
+
+ def clear_current_user
+ Auditor::User.current_user = nil
+ end
+
+ def verify_audit(audit, audited, user, action, edits_nil=false, message_nil=true)
+ audit.auditable_id.should == audited.id
+ audit.auditable_type.should == audited.class.name
+ audit.user_id.should == user.id
+ audit.user_type.should == user.class.name
+ audit.action.should == action.to_s
+ audit.message.should be_nil if message_nil
+ audit.message.should_not be_nil unless message_nil
+ audit.edits.should be_nil if edits_nil
+ audit.edits.should_not be_nil unless edits_nil
+ end
+
+end
+
+
14 spec/thread_local_spec.rb
@@ -0,0 +1,14 @@
+require File.dirname(__FILE__) + '/spec_helper'
+require 'auditor/thread_local'
+
+describe Auditor::ThreadLocal do
+ it "should properly set and get thread-local variables" do
+ val = "val"
+ tl = Auditor::ThreadLocal.new(val)
+ tl.get.should == val
+
+ val2 = "val2"
+ tl.set val2
+ tl.get.should == val2
+ end
+end
16 spec/thread_status_spec.rb
@@ -0,0 +1,16 @@
+require File.dirname(__FILE__) + '/spec_helper'
+require 'auditor'
+
+describe Auditor::ThreadStatus do
+ it "should be enabled if set to enabled" do
+ Auditor::ThreadStatus.enable
+ Auditor::ThreadStatus.should be_enabled
+ Auditor::ThreadStatus.should_not be_disabled
+ end
+
+ it "should be disabled if set to disabled" do
+ Auditor::ThreadStatus.disable
+ Auditor::ThreadStatus.should_not be_enabled
+ Auditor::ThreadStatus.should be_disabled
+ end
+end
25 spec/user_spec.rb
@@ -0,0 +1,25 @@
+require File.dirname(__FILE__) + '/spec_helper'
+require 'auditor/user'
+
+describe Auditor::User do
+ it "should return the same user that's set on the same thread" do
+ user = "user"
+ Auditor::User.current_user = user
+ Auditor::User.current_user.should == user
+ end
+
+ it "should not return the same user from a different thread" do
+ user = "user"
+ user2 = "user2"
+
+ Auditor::User.current_user = user
+
+ Thread.new do
+ Auditor::User.current_user.should be_nil
+ Auditor::User.current_user = user2
+ Auditor::User.current_user.should == user2
+ end
+
+ Auditor::User.current_user.should == user
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.