File: if_test.rb

package info (click to toggle)
ruby-representable 3.0.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 896 kB
  • sloc: ruby: 6,432; makefile: 3
file content (79 lines) | stat: -rw-r--r-- 2,336 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
require 'test_helper'

class IfTest < Minitest::Spec
  let(:band_class) { Class.new do
    include Representable::Hash
    attr_accessor :fame
    self
  end }

  it "respects property when condition true" do
    band_class.class_eval { property :fame, :if => lambda { |*| true } }
    band = band_class.new
    band.from_hash({"fame"=>"oh yes"})
    assert_equal "oh yes", band.fame
  end

  it "ignores property when condition false" do
    band_class.class_eval { property :fame, :if => lambda { |*| false } }
    band = band_class.new
    band.from_hash({"fame"=>"oh yes"})
    assert_nil band.fame
  end

  it "ignores property when :exclude'ed even when condition is true" do
    band_class.class_eval { property :fame, :if => lambda { |*| true } }
    band = band_class.new
    band.from_hash({"fame"=>"oh yes"}, {:exclude => [:fame]})
    assert_nil band.fame
  end

  it "executes block in instance context" do
    band_class.class_eval { property :fame, :if => lambda { |*| groupies }; attr_accessor :groupies }
    band = band_class.new
    band.groupies = true
    band.from_hash({"fame"=>"oh yes"})
    assert_equal "oh yes", band.fame
  end

  describe "executing :if lambda in represented instance context" do
    representer! do
      property :label, :if => lambda { |*| signed_contract }
    end

    subject { OpenStruct.new(:signed_contract => false, :label => "Fat") }

    it "skips when false" do
      subject.extend(representer).to_hash.must_equal({})
    end

    it "represents when true" do
      subject.signed_contract= true
      subject.extend(representer).to_hash.must_equal({"label"=>"Fat"})
    end

    it "works with decorator" do
      rpr = representer
      Class.new(Representable::Decorator) do
        include Representable::Hash
        include rpr
      end.new(subject).to_hash.must_equal({})
    end
  end


  describe "propagating user options to the block" do
    representer! do
      property :name, :if => lambda { |opts| opts[:user_options][:include_name] }
    end
    subject { OpenStruct.new(:name => "Outbound").extend(representer) }

    it "works without specifying options" do
      subject.to_hash.must_equal({})
    end

    it "passes user options to block" do
      subject.to_hash(user_options: { include_name: true }).must_equal({"name" => "Outbound"})
    end
  end
end