Module: Rspec::Rails23::Mocking::WithMocha

Defined in:
lib/rspec/rails23/mocking/with_mocha.rb

Instance Method Summary collapse

Instance Method Details

#add_stubs(object, params) ⇒ Object

Stubs methods on object (if object is a symbol or string a new mock with that name will be created). stubs is a Hash of method=>value



23
24
25
26
27
# File 'lib/rspec/rails23/mocking/with_mocha.rb', line 23

def add_stubs(object, params) # :nodoc:
  m = [String, Symbol].include?(object.class) ? mock(object.to_s) : object
  params.each { |prop, value| m.stubs(prop).returns(value) }
  m
end

#mock_model(model_class, params = {}) {|model| ... } ⇒ Object

Yields:

  • (model)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/rspec/rails23/mocking/with_mocha.rb', line 29

def mock_model(model_class, params = {})
id = params[:id] || next_id
model = stub("#{model_class.name}_#{id}", {
  :id => id,
  :to_param => id.to_s,
  :new_record? => false,
  :errors => stub("errors", :count => 0)
  }.update(params))

  model.instance_eval <<-CODE
  def as_new_record
    self.stubs(:id).returns(nil)
    self.stubs(:to_param).returns(nil)
    self.stubs(:new_record?).returns(true)
    self
  end
  def is_a?(other)
    #{model_class}.ancestors.include?(other)
  end
  def kind_of?(other)
    #{model_class}.ancestors.include?(other)
  end
  def instance_of?(other)
    other == #{model_class}
  end
  def class
    #{model_class}
  end
  CODE

  yield model if block_given?
  return model
end

#stub_model(model_class, params = {}) {|model| ... } ⇒ Object

Yields:

  • (model)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/rspec/rails23/mocking/with_mocha.rb', line 6

def stub_model(model_class, params = {})
  params = params.dup
  model = model_class.new
  model.id = params.delete(:id) || next_id
  model.extend ::Rspec::Rails23::Mocking::ModelStubber
  
  params.keys.each do |prop|
    model[prop] = params.delete(prop) if model.has_attribute?(prop)
  end
  add_stubs(model, params)

  yield model if block_given?
  model
end