Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ObjectCreationMethods a la Jeff Dean
#lives in spec/support/object_creation_methods.rb
# Source: https://pivotallabs.com/users/jdean/blog/articles/1900-rolling-your-own-object-creation-methods-for-specs
module ObjectCreationMethods
def new_post(overrides = {})
defaults = {:title => "Some title #{counter}"}
Post.new { |post| apply(post, defaults, overrides) }
end
def create_post(overrides = {})
new_post(overrides).tap(&:save!)
end
def new_comment(overrides = {})
defaults = {:post => proc { new_post }, :text => "some text"}
Comment.new { |comment| apply(comment, defaults, overrides) }
end
def create_comment(overrides = {})
new_comment(overrides).tap(&:save!)
end
private
# with this code you can remove all your create methods
def method_missing(method, *args, &block)
new_method = method.to_s.gsub(/^create_/,'new_')
if method.to_s != new_method && self.respond_to?(new_method)
send(new_method, *args).tap(&:save!)
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
method_name.to_s.start_with?('create_') || super
end
def counter
@counter ||= 0
@counter += 1
end
def apply(object, defaults, overrides)
options = defaults.merge(overrides)
options.each do |method, value_or_proc|
object.send("#{method}=", value_or_proc.is_a?(Proc) ? value_or_proc.call : value_or_proc)
end
end
end
#lives in spec/spec_helper.rb
RSpec.configure do |config|
config.include ObjectCreationMethods
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment