enum_test.rb 1.9 KB
Newer Older
1 2 3
require 'cases/helper'
require 'models/book'

4
class EnumTest < ActiveRecord::TestCase
5 6 7
  fixtures :books

  setup do
8
    @book = books(:awdr)
9 10 11 12 13 14
  end

  test "query state by predicate" do
    assert @book.proposed?
    assert_not @book.written?
    assert_not @book.published?
Y
Yury Korolev 已提交
15 16

    assert @book.unread?
17
  end
18

R
Robin Dupret 已提交
19
  test "query state with strings" do
20 21
    assert_equal "proposed", @book.status
    assert_equal "unread", @book.read_status
22 23
  end

24 25
  test "find via scope" do
    assert_equal @book, Book.proposed.first
Y
Yury Korolev 已提交
26
    assert_equal @book, Book.unread.first
27 28
  end

29 30 31 32
  test "update by declaration" do
    @book.written!
    assert @book.written?
  end
33

34 35 36 37
  test "update by setter" do
    @book.update! status: :written
    assert @book.written?
  end
38 39 40 41 42

  test "enum methods are overwritable" do
    assert_equal "do publish work...", @book.published!
    assert @book.published?
  end
43 44 45 46 47 48

  test "direct assignment" do
    @book.status = :written
    assert @book.written?
  end

49 50 51 52 53
  test "assign string value" do
    @book.status = "written"
    assert @book.written?
  end

54 55 56 57 58 59
  test "assign non existing value raises an error" do
    e = assert_raises(ArgumentError) do
      @book.status = :unknown
    end
    assert_equal "'unknown' is not a valid status", e.message
  end
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  test "assign nil value" do
    @book.status = nil
    assert @book.status.nil?
  end

  test "assign empty string value" do
    @book.status = ''
    assert @book.status.nil?
  end

  test "assign long empty string value" do
    @book.status = '   '
    assert @book.status.nil?
  end

76 77 78 79 80
  test "constant to access the mapping" do
    assert_equal 0, Book::STATUS[:proposed]
    assert_equal 1, Book::STATUS["written"]
    assert_equal 2, Book::STATUS[:published]
  end
R
Robin Dupret 已提交
81 82 83 84 85 86 87 88 89

  test "first_or_initialize with enums' scopes" do
    class Issue < ActiveRecord::Base
      enum status: [:open, :closed]
    end

    assert Issue.open.empty?
    assert Issue.open.first_or_initialize
  end
90
end