Skip to content

Instantly share code, notes, and snippets.

@feroult
Created February 7, 2011 21:07
Show Gist options
  • Save feroult/815220 to your computer and use it in GitHub Desktop.
Save feroult/815220 to your computer and use it in GitHub Desktop.
RSpec Macros Recorder
module MacrosBase
def self.included(base)
base.extend(GroupMethods)
end
module GroupMethods
def mock(model_name)
class_eval <<-EOFMOCK
def mock_#{model_name}(stubs={})
(@mock_#{model_name} ||= mock_model(#{model_name.to_s.classify}).as_null_object).tap do |#{model_name}|
#{model_name}.stub(stubs) unless stubs.empty?
end
end
EOFMOCK
end
def default_model(model_name)
mock(model_name)
class_eval <<-EOFDEFAULTMOCK
alias :model_mock :mock_#{model_name}
def model_class
#{model_name.to_s.classify}
end
def collection_sym
:#{model_name.to_s.pluralize}
end
def member_sym
:#{model_name}
end
def collection_url
#{model_name.to_s.pluralize}_url
end
def member_url(customer)
#{model_name}_url(customer)
end
def collection_path
#{model_name.to_s.pluralize}_path
end
def member_path(customer)
#{model_name}_path(customer)
end
EOFDEFAULTMOCK
end
def add_macro(macro_method, name, params = {}, &block)
macro = Macro.new(macro_method, name, params)
if macro_templates[name]
macro_templates[name].each { |template_block| macro.instance_eval(&template_block) }
end
macro.instance_eval(&block) if block_given?
send(:describe_macro, macro)
end
def create_macros(*macros)
macros.each do |macro_method|
instance_eval <<-EOFHTTPMETHOD
def #{macro_method}(name, params = {}, &block)
add_macro("#{macro_method}", name, params, &block)
end
EOFHTTPMETHOD
end
end
def macro_templates
@macro_templates ||= {}
end
def macro_template(name, &block)
macro_templates[name] ||= []
macro_templates[name] << block
end
alias :append_template :macro_template
class Macro
def initialize(macro_method, name, params = {})
@macro_method = macro_method
@name = name
set(params)
end
def full_description
"#{@macro_method.to_s.upcase} #{name}" + (@description ? " (#{@description})" : "")
end
def macro_method
@macro_method
end
def name
@name
end
def default(options = {})
options.each do |(option, value)|
disable << option if value == :off
end
end
def disable
@disable ||= []
end
def enable?(option)
!disable.include?(option)
end
def params
@params ||= {}
end
def set(params)
self.params.merge!(params)
end
def description(description)
@description = description
end
def customs
@customs ||= []
end
def custom?(method)
customs.index { |custom| method == custom[0] }
end
def delete_custom(method)
deleted = customs.select { |custom| method == custom[0] }
if deleted.empty?
nil
else
customs.delete_if { |custom| method == custom[0] }
deleted
end
end
def method_missing(method, *args, &block)
customs << [method, args, block]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment