File: rule.rb

package info (click to toggle)
ruby-dry-logic 1.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 728 kB
  • sloc: ruby: 4,929; makefile: 6
file content (74 lines) | stat: -rw-r--r-- 1,849 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
# frozen_string_literal: true

RSpec.shared_examples_for Dry::Logic::Rule do
  let(:arity) { 2 }
  let(:predicate) { double(:predicate, arity: arity, name: predicate_name) }
  let(:rule_type) { described_class }
  let(:predicate_name) { :good? }

  describe "#arity" do
    it "returns its predicate arity" do
      rule = rule_type.build(predicate)

      expect(rule.arity).to be(2)
    end
  end

  describe "#parameters" do
    it "returns a list of args with their names" do
      rule = rule_type.build(-> foo, bar { true }, args: [312])

      expect(rule.parameters).to eql([%i[req foo], %i[req bar]])
    end
  end

  describe "#call" do
    let(:arity) { 1 }

    it "returns success for valid input" do
      rule = rule_type.build(predicate)

      expect(predicate).to receive(:[]).with(2).and_return(true)

      expect(rule.(2)).to be_success
    end

    it "returns failure for invalid input" do
      rule = rule_type.build(predicate)

      expect(predicate).to receive(:[]).with(2).and_return(false)

      expect(rule.(2)).to be_failure
    end
  end

  describe "#[]" do
    let(:arity) { 1 }

    it "delegates to its predicate" do
      rule = rule_type.build(predicate)

      expect(predicate).to receive(:[]).with(2).and_return(true)
      expect(rule[2]).to be(true)
    end
  end

  describe "#curry" do
    it "returns a curried rule" do
      rule = rule_type.build(predicate).curry(3)

      expect(predicate).to receive(:[]).with(3, 2).and_return(true)
      expect(rule.args).to eql([3])

      expect(rule.(2)).to be_success
    end

    it "raises argument error when arity does not match" do
      expect(predicate).to receive(:arity).and_return(2)

      expect { rule_type.build(predicate).curry(3, 2, 1) }.to raise_error(
        ArgumentError, "wrong number of arguments (3 for 2)"
      )
    end
  end
end