Rails 唯一性验证测试失败

use*_*174 3 testing validation ruby-on-rails unique

我从 Rails 4.2 开始,我尝试测试我正在制作的 Item 模型的唯一性,我运行了以下代码:

项目.rb:

class Item < ActiveRecord::Base
    attr_accessor :name
    validates :name, uniqueness: true #, other validations...
end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

但是测试没有通过,说assert_not线路true在应该出来的时候出来了nil或者false。我基本上从教程中得到了这段代码,但不知道为什么它没有通过。有什么帮助吗?

编辑:我找到了解决方案,通过不定义我在操作中定义的其他成员(特别是:price),测试通过了。但是现在我不知道如何让它通过成员。下面是 item.rb 和 item_test.rb 的完整实现。@itemsetup:price

项目.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 
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Pra*_*thy 5

上面 Almaron 的答案是正确的,应该是公认的答案。

我正在添加这个答案来详细说明它。

测试如下:

require 'test_helper'

class ItemTest < ActiveSupport::TestCase

  def setup
    @item = Item.create(name: "Example Item")
  end

  test "name should be unique" do
    duplicate_item = @item.dup
    assert_not duplicate_item.valid?
  end
end
Run Code Online (Sandbox Code Playgroud)

注意:duplicate_item在验证之前不需要保存。