Created
July 26, 2010 15:58
-
-
Save ngty/490743 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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