mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
788bb40e38
Previously, this would give an `ArgumentError`: class Issue < ActiveRecord::Base enum :status, [:open, :finished] end Issue.open.build # => ArgumentError: '0' is not a valid status Issue.open.create # => ArgumentError: '0' is not a valid status PR #13542 muted the error, but the issue remains. This commit fixes the issue by allowing the enum value to be written directly via the setter: Issue.new.status = 0 # This now sets status to :open Assigning a value directly via the setter like this is not part of the documented public API, so users should not rely on this behavior. Closes #13530.
91 lines
1.9 KiB
Ruby
91 lines
1.9 KiB
Ruby
require 'cases/helper'
|
|
require 'models/book'
|
|
|
|
class EnumTest < ActiveRecord::TestCase
|
|
fixtures :books
|
|
|
|
setup do
|
|
@book = books(:awdr)
|
|
end
|
|
|
|
test "query state by predicate" do
|
|
assert @book.proposed?
|
|
assert_not @book.written?
|
|
assert_not @book.published?
|
|
|
|
assert @book.unread?
|
|
end
|
|
|
|
test "query state with strings" do
|
|
assert_equal "proposed", @book.status
|
|
assert_equal "unread", @book.read_status
|
|
end
|
|
|
|
test "find via scope" do
|
|
assert_equal @book, Book.proposed.first
|
|
assert_equal @book, Book.unread.first
|
|
end
|
|
|
|
test "update by declaration" do
|
|
@book.written!
|
|
assert @book.written?
|
|
end
|
|
|
|
test "update by setter" do
|
|
@book.update! status: :written
|
|
assert @book.written?
|
|
end
|
|
|
|
test "enum methods are overwritable" do
|
|
assert_equal "do publish work...", @book.published!
|
|
assert @book.published?
|
|
end
|
|
|
|
test "direct assignment" do
|
|
@book.status = :written
|
|
assert @book.written?
|
|
end
|
|
|
|
test "assign string value" do
|
|
@book.status = "written"
|
|
assert @book.written?
|
|
end
|
|
|
|
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
|
|
|
|
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
|
|
|
|
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
|
|
|
|
test "building new objects with enum scopes" do
|
|
assert Book.written.build.written?
|
|
assert Book.read.build.read?
|
|
end
|
|
|
|
test "creating new objects with enum scopes" do
|
|
assert Book.written.create.written?
|
|
assert Book.read.create.read?
|
|
end
|
|
end
|