Rails 3.2:失败的断言唯一性:true

时间:2012-05-01 18:59:08

标签: ruby-on-rails-3.2

所有

我在测试模型时遇到问题,我有一个简单的客户表,它使用以下字段:name:string,location:string,full_name:string,active:boolean。我使用full_name字段作为隐藏字段,其中包含以下“#{name}#{location}”并在full_name字段上测试记录的唯一性。

测试“客户在没有唯一的full_name时无效”是我遇到问题的测试,我正在尝试测试重复记录的插入。如果我删除断言!customer.save前面的爆炸(!),测试将通过。这就像在运行测试之前没有加载到表中的灯具,我正在运行rake测试:单位。我尝试在开发模式下运行服务器并使用脚手架插入两个记录,第二次插入失败并报告错误“已经采取了全名”这是预期的行为。

任何人都可以给我一些关于我搞砸了测试的指导!

提前致谢

瑞贝克


型号:

class Customer < ActiveRecord::Base
  attr_accessible :active, :full_name, :location, :name

  validates :active, :location, :name, presence: true
  validates :full_name, uniqueness: true              # case I am trying to test

  before_validation :build_full_name

  def build_full_name
    self.full_name = "#{name} #{location}"
  end

end

测试夹具customers.yml

one:
  name: MyString
  location: MyString
  full_name: MyString
  active: false

two:
  name: MyString
  location: MyString
  full_name: MyString
  active: false

general:
  name: 'Whoever'
  location: 'Any Where'
  full_name: ''
  active: true

测试单位助手customer_test.rb

require 'test_helper'

class CustomerTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true 
  # end

  fixtures :customers

  # Test fields have to be present
  test "customer fields must not be empty" do
    customer = Customer.new
    assert customer.invalid?
    assert customer.errors[:name].any?
    assert customer.errors[:location].any?
    assert_equal " ", customer.full_name     # This is processed by a helper function in the model
    assert customer.errors[:active].any?
  end

  # Test full_name field is unique
  test "customer is not valid without a unique full_name" do
    customer = Customer.new(
    name: customers(:general).name,
    location: customers(:general).location,
    full_name: customers(:general).full_name,
    active: customers(:general).active
    )

    assert !customer.save   # this is the line that fails
    assert_equal "has already been taken", customer.errors[:full_name].join(', ')
  end

end

1 个答案:

答案 0 :(得分:0)

我在夹具customers.yml:

中发现了问题

我假设将通过模型处理fixture,并且在将数据插入测试数据库之前将调用build_full_name助手。情况似乎并非如此。

我更改了夹具,如下所示,它纠正了问题:

one:
 name: MyString
 location: MyString
 full_name: MyString
 active: false

two:
 name: MyString2         # changed for consistency, was not the problem
 location: MyString2
 full_name: MyString2
 active: false

general:
 name: 'Whoever'
 location: 'Any Where'
 full_name: 'Whoever Any Where'  #Here was the problem
 active: true