Skip to content

Instantly share code, notes, and snippets.

@sneakin
Created February 25, 2009 19:32
Show Gist options
  • Save sneakin/70362 to your computer and use it in GitHub Desktop.
Save sneakin/70362 to your computer and use it in GitHub Desktop.
rSpec macro to help w/ controller action specs
# Copyright (C) 2009 SemanticGap(R)
#
# 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.
#
# To use this, you should place the following in your `spec/spec_helper.rb`
# after loading the module:
#
# DoActionGenerator.default_params = { :css => 'desktop', :format => 'html' }
#
# module Spec
# module Rails
# module Example
# class ControllerExampleGroup < FunctionalExampleGroup
# include DoActionGenerator
# end
# end
# end
# end
#
module DoActionGenerator
mattr_accessor :default_params
def self.included(base)
base.extend(ClassMethods)
end
def infer_method(action)
case action.to_sym
when :update then :put
when :create then :post
else :get
end
end
module ClassMethods
def do_action(action_name, method = nil, default_params = Hash.new, &block)
define_method("params") do
if DoActionGenerator.default_params
params = DoActionGenerator.default_params.dclone
else
params = Hash.new
end
params.merge!(default_params)
params.merge!(self.instance_eval(&block)) if block
params
end
define_method("do_action") do |*args|
send(method || infer_method(action_name),
action_name,
self.params.merge(args.last || Hash.new))
end
end
def action(name, param_proc = nil, method = nil, &block)
param_proc = proc { param_proc } if param_proc && !param_proc.kind_of?(Proc)
d = describe name do
do_action name, method, &param_proc
end
d.instance_eval(&block)
d
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment