enum_test.rb 2.1 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
  test "constant to access the mapping" do
77 78 79
    assert_equal 0, Book.statuses[:proposed]
    assert_equal 1, Book.statuses["written"]
    assert_equal 2, Book.statuses[:published]
80
  end
R
Robin Dupret 已提交
81

82 83 84 85
  test "building new objects with enum scopes" do
    assert Book.written.build.written?
    assert Book.read.build.read?
  end
R
Robin Dupret 已提交
86

87 88 89
  test "creating new objects with enum scopes" do
    assert Book.written.create.written?
    assert Book.read.create.read?
R
Robin Dupret 已提交
90
  end
91 92 93 94

  test "_before_type_cast returns the enum label (required for form fields)" do
    assert_equal "proposed", @book.status_before_type_cast
  end
95
end