验证包含值时验证错误:Rails

时间:2016-02-12 08:03:45

标签: ruby ruby-on-rails-3 validation ruby-on-rails-4 testing

我在模型验证中测试包含时遇到错误。这是我的model.rb

class Resident < ActiveRecord::Base
  validates :room_number,presence: true,uniqueness: {case_sensitive: false}
  validates :roll_number,presence: true,uniqueness:{case_sensitive: false}
  validates :name, presence: true,length: { maximum: 50 }
  validates :hostel,presence: true,inclusion: {in:%w(a b c h pg j frc e g i),message: "%{value} is not a valid hostel"}
end

model_test.rb only inclusion test

 test "hostel must be valid" do
    if @resident.hostel == %w(a b c h pg j frc e g i)
      assert @resident.valid?
    else
      assert_not @resident.valid?
    end

我收到此错误

     test_should_be_valid#ResidentTest (1455250549.01s)
        Failed assertion, no message given.
        test/models/resident_test.rb:9:in `block in <class:ResidentTest>'
8 tests, 8 assertions, 1 failures, 0 errors, 0 skips

我该如何处理它。

1 个答案:

答案 0 :(得分:0)

我认为您应该尝试在测试中创建Resident的实例,并使用有效或无效的宿舍属性。然后你应该检查你的期望。

test "hostel must be valid" do
  resident = Resident.create(@valid_attributes.merge({:hostel => 'a'})
  assert resident.valid?
end

test "hostel must be invalid" do
  resident = Resident.create(@valid_attributes.merge({:hostel => 'z'})
  assert_not resident.valid?
end

请注意:%w(a b c h pg j frc e g i)是一个字符串数组。 if @resident.hostel == %w(a b c h pg j frc e g i)无法正常工作,因为您检查了一个字符串(我认为)对阵数组。