Skip to content

Instantly share code, notes, and snippets.

@durran
Created December 1, 2009 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durran/246522 to your computer and use it in GitHub Desktop.
Save durran/246522 to your computer and use it in GitHub Desktop.
Given /^the following (.+?)(|\s+only)$/ do |model_name, only, table|
parser = Mongoid::Cucumber::Parser.new(model_name)
model, klass = parser.model, parser.klass
klass.destroy_all if only =~ /only$/
@objects = Mongoid::Cucumber::Factory.create(klass, table)
@objects.each(&:save!)
@object = @objects.last if @objects.size == 1
instance_variable_set("@#{model}", @object)
end
Given /^(?:the )?(.*?) (?:has|have) the following (.+?)$/ do |parent_name, association_name, table|
parent_name.gsub!(/\s/, '_')
parent = instance_variable_get("@#{parent_name}")
parser = Mongoid::Cucumber::Parser.new(association_name)
model, klass = parser.model, parser.klass
@children = Mongoid::Cucumber::Factory.create(klass, table)
parent.send("#{association_name}=", @children)
parent.save!
instance_variable_set("@#{association_name}", @children.first)
end
module Mongoid
module Cucumber
class Factory
def self.create(klass, table)
objects = table.hashes.map do |hash|
attributes = hash.dup.inject({}) do |h, (k, v)|
h.delete(k)
h.update(k.gsub(/\s+/, "_") => v)
end
object = klass.make(attributes)
end
end
end
class Parser
def initialize(name)
@name = name
end
def model
@name.parameterize("_").singularize.to_sym
end
def klass
model.to_s.classify.constantize
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment