全部,
我在测试模型时遇到问题,我有一个简单的客户表,它使用以下字段:名称:字符串、位置:字符串、全名:字符串、活动:布尔值。我将 full_name 字段用作包含以下“#{name} #{location}”的隐藏字段,并在 full_name 字段上测试记录的唯一性。
测试“如果没有唯一的全名,客户无效”是我遇到问题的测试,我正在尝试测试重复记录的插入。如果我删除 assert !customer.save 前面的 bang(!) 测试将通过。这就像在运行测试之前没有将固定装置加载到表中一样,我正在运行 rake test:units。我尝试在开发模式下运行服务器并使用脚手架插入两条记录,第二次插入失败并报告错误“全名已被采用”,这是预期的行为。
谁能给我一些关于我在哪里搞砸测试的指导!
提前致谢
回退
模型:
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