【发布时间】:2015-03-15 08:38:22
【问题描述】:
我从 Rails 4.2 开始,我正在尝试测试我正在制作的 Item 模型的唯一性,我运行了以下代码:
item.rb:
class Item < ActiveRecord::Base
attr_accessor :name
validates :name, uniqueness: true #, other validations...
end
item_test.rb:
require 'test_helper'
class ItemTest < ActiveSupport::TestCase
def setup
@item = Item.new(name: "Example Item")
end
test "name should be unique" do
duplicate_item = @item.dup
@item.save
assert_not duplicate_item.valid?
end
end
但测试没有通过,说assert_not 行出来了true,而它应该是nil 或false。我基本上从教程中得到了这段代码,但无法弄清楚为什么它没有通过。有什么帮助吗?
编辑:我找到了解决方案,通过不定义我在 setup 操作中定义的 @item 的其他成员(特别是 :price ),测试通过了。但是现在我不知道如何让它通过:price 成员。下面是 item.rb 和 item_test.rb 的完整实现。
item.rb:
class Item < ActiveRecord::Base
attr_accessor :name, :description, :price
validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
validates :description, presence: true,
length: { maximum: 1000 }
VALID_PRICE_REGEX = /\A\d+(?:\.\d{0,2})?\z/
validates :price, presence: true,
:format => { with: VALID_PRICE_REGEX },
:numericality => {:greater_than => 0}
end
item_test.rb:
require 'test_helper'
class ItemTest < ActiveSupport::TestCase
def setup
@item = Item.new(name: "Example Item", description: "Some kind of item.", price: 1.00)
end
test "name should be unique" do
duplicate_item = @item.dup
@item.save
assert_not duplicate_item.valid?
end
end
【问题讨论】:
标签: ruby-on-rails validation testing unique