Skip to content

Instantly share code, notes, and snippets.

@ngty
Created July 26, 2010 15:58
Show Gist options
  • Save ngty/490743 to your computer and use it in GitHub Desktop.
Save ngty/490743 to your computer and use it in GitHub Desktop.
module RailsBestPractices
module Macros
def self.included(base)
# Calling of "include RailsBestPractices::Macros" will make all macros available as
# class methods within describe { ... }
base.extend(ClassMethods)
end
module ClassMethods
def should_be_user_ownable(factory_id = nil)
# default_factory_id (see below) should be able to derive a sensible one, but may
# be exception (a little over-engineered, but a simple one)
factory_id ||= default_factory_id
# generates an example group
describe 'being user ownable' do
# The rest are just relocated from original spec, with the replacing of hardcoded
# factory name with factory_id
should_belong_to :user
it 'should belong to someone if he is the owner of it' do
someone = Factory(:user)
Factory(factory_id, :user => someone).belongs_to?(someone).should be_true
end
it 'should not belong to someone if he is not the owner of it' do
someone = Factory(:user)
Factory(factory_id).belongs_to?(someone).should be_false
end
end
end
private
def default_factory_id
# derive a factory name, based on the current context class
context_klass.to_s.tableize.singularize.to_sym
end
def context_klass
# NOTE: This part is abit brittle, assumes the the context description to be a
# stringified class name or the class itself, Eg:
#
# Works for:
# - describe Customer::PurchaseOrder { ... }
# - describe 'Customer::PurchaseOrder' { ... }
#
# BUT not for:
# - describe 'Customer Purchase Order' { ... }
#
self.description.split('::').inject(Object) {|klass, const| klass.const_get(const) }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment