Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tag: v0.0.1
Fetching contributors…

Cannot retrieve contributors at this time

file 110 lines (83 sloc) 2.261 kb
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
require "minitest/autorun"
require "mocha"
require "watchable"

describe Watchable do
  before do
    @obj = Object.new
    @obj.extend Watchable
  end

  it "has an empty list of watchers by default" do
    assert @obj.watchers.empty?
  end

  it "returns an empty array of watchers for any event" do
    assert_equal [], @obj.watchers[:foo]
  end

  describe :fire do
    it "calls each watcher with optional args" do
      @obj.on :foo, mock { expects(:call).with :bar, :baz }
      @obj.fire :foo, :bar, :baz
    end

    it "calls multiple watchers in order" do
      fires = sequence "fires"

      @obj.on :foo, mock { expects(:call).in_sequence fires }
      @obj.on :foo, mock { expects(:call).in_sequence fires }

      @obj.fire :foo
    end

    it "returns the watchable" do
      assert_same @obj, @obj.fire(:foo)
    end
  end

  describe :off do
    it "can unregister a block" do
      b = lambda {}

      @obj.on :foo, &b
      @obj.off :foo, &b

      assert @obj.watchers[:foo].empty?
    end

    it "can unregister an object" do
      b = lambda {}

      @obj.on :foo, &b
      @obj.off :foo, &b

      assert @obj.watchers[:foo].empty?
    end

    it "can unregister all watchers for an event" do
      @obj.on(:foo) {}
      @obj.on(:foo) {}

      assert_equal 2, @obj.watchers[:foo].size

      @obj.off :foo
      assert @obj.watchers[:foo].empty?
    end

    it "returns the watchable" do
      assert_same @obj, @obj.off(:foo)
    end
  end

  describe :on do
    it "can register a block" do
      b = lambda {}

      @obj.on :foo, &b
      assert_equal [b], @obj.watchers[:foo]
    end

    it "can register an object" do
      b = lambda {}

      @obj.on :foo, b
      assert_equal [b], @obj.watchers[:foo]
    end

    it "can register for all events" do
      @obj.on :all, mock { expects(:call).with :foo, :bar }
      @obj.fire :foo, :bar
    end

    it "returns the watchable" do
      assert_same @obj, @obj.on(:foo) {}
    end
  end

  describe :once do
    it "registers a watcher that's only called on the first fire" do
      @obj.once :foo, mock { expects :call }

      @obj.fire :foo
      @obj.fire :foo
    end

    it "returns the watchable" do
      assert_same @obj, @obj.once(:foo) {}
    end
  end
end
Something went wrong with that request. Please try again.