class CleanMock
Attributes
model[R]
Public Class Methods
attributes_for(*args)
click to toggle source
# File lib/clean-mock/base.rb, line 15 def attributes_for *args build(*args).attributes.select{ |k,v| v.present? } end
build(*args)
click to toggle source
create a new model, no save
# File lib/clean-mock/base.rb, line 20 def build *args new(*args).model end
create(*args)
click to toggle source
save if possible
# File lib/clean-mock/base.rb, line 25 def create *args build(*args).tap do |model| model.save if model.respond_to?(:save) end end
define(name, opts={})
click to toggle source
defined mocked model
# File lib/clean-mock/base.rb, line 11 def define name, opts={}, &block @@mock_data[name] = [block, opts] end
fetch(*args, &block)
click to toggle source
create only once
# File lib/clean-mock/base.rb, line 32 def fetch *args, &block code = Digest::SHA1.hexdigest(args.to_s) @@fetched[code] ||= create(*args, &block) end
new(*args)
click to toggle source
# File lib/clean-mock/base.rb, line 40 def initialize *args opts = args.last.is_a?(Hash) ? args.pop : {} @kind = args.shift @traits = args block, mock_opts = @@mock_data[@kind] || raise(ArgumentError, 'Mock model "%s" not defined' % @kind) @model = case mock_opts[:class] when FalseClass # define :foo, class: false nil when NilClass # define :foo @kind.to_s.classify.constantize.new when Symbol # define :foo, class: foo name = mock_opts[:class].to_s.classify if Object.const_defined?(name) name.constantize.new else Object.const_set(name, Class.new).new end else # define :foo, class: FooBar mock_opts[:class].new end if @model instance_exec @model, opts, &block else @model = instance_exec opts, &block end raise 'Trait [%s] not found' % @traits.join(', ') if @traits.first end
Public Instance Methods
create(name, field=nil)
click to toggle source
helper to create and link model create :org -> @model.org_id = mock.create(org).id
# File lib/clean-mock/base.rb, line 99 def create name, field=nil field ||= name.to_s.singularize + '_id' new_model = CleanMock.create(name) @model.send('%s=' % field, new_model.id) new_model end
func(name, &block)
click to toggle source
define or overlod current instance method
# File lib/clean-mock/base.rb, line 86 def func name, &block @model.define_singleton_method(name, &block) end
sequence(name=nil, start=nil)
click to toggle source
simple sequence generator by name
# File lib/clean-mock/base.rb, line 91 def sequence name=nil, start=nil name ||= :seq @@sequence[name] ||= start || 0 @@sequence[name] += 1 end
trait(name, &block)
click to toggle source
block to execute and modify model
# File lib/clean-mock/base.rb, line 79 def trait name, &block if @traits.delete(name) instance_exec(@model, &block) end end