2012-05-01 22 views
1

所有,Rails的3.2:失败断言独特性:真实

我有测试模型的麻烦,我有一个使用以下字段一个简​​单的客户表:姓名:字符串,地点:字符串,FULL_NAME:字符串,积极:布尔。我将full_name字段用作包含以下“#{name}#{location}”的隐藏字段,并在full_name字段中测试记录的唯一性。

测试“客户是无效的没有唯一的全名”是测试,我有一个问题,我试图测试插入的重复记录。如果我删除assert!customer.save前面的爆炸(!),测试将通过。这是行动像运行测试之前,夹具没有被加载到表中,我正在运行耙测试:单位。我尝试在开发模式下运行服务器,并使用脚手架插入两条记录,第二次插入失败,并报告出现“预先已知的全名”错误,这是预期的行为。

任何人都可以给我一些指导,我已经搞砸了测试!

在此先感谢

瑞贝克


型号:

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 

回答

0

我发现在夹具customers.yml问题:

我认为夹具将通过该模式,且在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