Class: CouchPotato::RSpec::StubView::ViewStub

Inherits:
Object
  • Object
show all
Includes:
RSpec::Mocks::ExampleMethods
Defined in:
lib/couch_potato/rspec/stub_db.rb

Instance Method Summary collapse

Constructor Details

#initialize(clazz, view, db) ⇒ ViewStub

Returns a new instance of ViewStub.



11
12
13
14
15
# File 'lib/couch_potato/rspec/stub_db.rb', line 11

def initialize(clazz, view, db)
  @clazz = clazz
  @view = view
  @db = db
end

Instance Method Details

#and_return(*return_values) ⇒ Object



23
24
25
26
27
28
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
# File 'lib/couch_potato/rspec/stub_db.rb', line 23

def and_return(*return_values)
  view_stub = double("#{@clazz}.#{@view}(#{@args.try(:join, ', ')}) view")
  stub = allow(@clazz).to receive(@view)
  stub.with(*@args) if @args
  stub.and_return(view_stub)

  view_return_values = return_values.map do |return_value|
    if flex_view? && return_value.is_a?(Array)
      stub_flex_results(return_value)
    else
      return_value
    end
  end
  allow(@db).to receive(:view).with(view_stub).and_return(*view_return_values)
  return unless return_values.all? { |v| v.respond_to?(:first) }

  allow(@db).to receive(:first).with(view_stub).and_return(*return_values.map(&:first))
  remaining_for_batches = return_values.dup
  allow(@db)
    .to receive(:view_in_batches) do |_view, batch_size: CouchPotato::Database.default_batch_size, &block|
      return_value = remaining_for_batches.size > 1 ? remaining_for_batches.shift : remaining_for_batches.first
      batches = return_value.in_groups_of(batch_size, false)
      batches.each(&block)
    end
    .with(view_stub, any_args)

  remaining_for_first = return_values.dup
  allow(@db).to receive(:first!).with(view_stub) do
    return_value = remaining_for_first.size > 1 ? remaining_for_first.shift : remaining_for_first.first
    raise CouchPotato::NotFound unless return_value.first

    return_value.first
  end
end

#with(*args, &block) ⇒ Object



17
18
19
20
21
# File 'lib/couch_potato/rspec/stub_db.rb', line 17

def with(*args, &block)
  @args = args
  and_return(block.call) if block
  self
end