【问题标题】:Validation error while validating inclusion values:Rails验证包含值时出现验证错误:Rails
【发布时间】:2016-02-12 08:03:45
【问题描述】:

我在测试包含在我的模型验证中时遇到错误。这是我的 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 仅包含测试

 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

我该如何处理它。

【问题讨论】:

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


    【解决方案1】:

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

    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) 不能工作,因为你检查一个字符串(我认为)对照一个数组。

    【讨论】:

    • 这里merge的作用是什么?在if语句中检查字符串数组是否断言是不对的,也许我们可以在if语句中一一比较字符串
    • Merge 将新哈希放入现有的 @valid_attributes 哈希中。因此它会添加新的键:值对或更改现有键的值:ruby-doc.org/core-2.3.0/Hash.html#method-i-merge
    • 您的包含验证检查单个属性是否具有数组的一个/一个值,但在您的测试中,您寻找数组 == 字符串的相等性。结果是假的。你可以检查一下:%w(a b c h pg j frc e g i).include?(resident.hostel)
    • test "hostel must be valid" do if %w(a b c h pg j frc e g i).include?(@resident.hostel) assert @resident.valid? else assert_not @resident.valid? end 还是一样的8 tests, 8 assertions, 1 failures, 0 errors, 0 skips
    • 要明确model_test.rbresident_test.rb 相同?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    相关资源
    最近更新 更多