Module: ViewModel::TestHelpers

Extended by:
ActiveSupport::Concern
Defined in:
lib/view_model/test_helpers.rb

Overview

Helpers useful for writing tests for viewmodel implementations

Defined Under Namespace

Classes: ARVMBuilder

Instance Method Summary collapse

Instance Method Details

#alter_by_view!(viewmodel_class, model, serialize_context: viewmodel_class.new_serialize_context, deserialize_context: viewmodel_class.new_deserialize_context) ⇒ Object

Test helper: update a model by manipulating the full view hash



22
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
# File 'lib/view_model/test_helpers.rb', line 22

def alter_by_view!(viewmodel_class, model,
                   serialize_context:   viewmodel_class.new_serialize_context,
                   deserialize_context: viewmodel_class.new_deserialize_context)

  models = Array.wrap(model)

  data, refs = serialize_with_references(models.map { |m| viewmodel_class.new(m) }, serialize_context: serialize_context)

  if model.is_a?(Array)
    yield(data, refs)
  else
    yield(data.first, refs)
  end

  begin
    result = viewmodel_class.deserialize_from_view(
      data, references: refs, deserialize_context: deserialize_context)

    result.each do |vm|
      assert_consistent_record(vm)
    end

    result = result.first unless model.is_a?(Array)

    models.each { |m| m.reload }

    return result, deserialize_context
  end
end

#serialize(serializable, serialize_context: ViewModel.new_serialize_context) ⇒ Object



16
17
18
19
# File 'lib/view_model/test_helpers.rb', line 16

def serialize(serializable, serialize_context: ViewModel.new_serialize_context)
  data, _ = serialize_with_references(serializable, serialize_context: serialize_context)
  data
end

#serialize_with_references(serializable, serialize_context: ViewModel.new_serialize_context) ⇒ Object



10
11
12
13
14
# File 'lib/view_model/test_helpers.rb', line 10

def serialize_with_references(serializable, serialize_context: ViewModel.new_serialize_context)
  data = ViewModel.serialize_to_hash(serializable, serialize_context: serialize_context)
  references = serialize_context.serialize_references_to_hash
  return data, references
end