ruby - 验证包含值时出现验证错误 :Rails

标签 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 仅包含测试

 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

我该如何处理。

最佳答案

我认为您应该首先尝试在您的测试中创建一个 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) 无法工作,因为您要根据数组检查字符串(我认为)。

关于ruby - 验证包含值时出现验证错误 :Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35357543/

相关文章:

asp.net-mvc-2 - 为什么 ValidationMessageFor 在这种情况下不显示我的验证消息?

php - 如何解决 Laravel-5.4 多列的输入值唯一验证

ruby-on-rails - link_to_remote 想要呈现一个模板 - 怎么不呢? rails

Ruby 类,我怀疑我做错了实例标记

ruby - 对 gsub 中的每个插入实例使用不同的结果

ruby-on-rails - 你如何让这个 div 环绕图像链接?

ruby-on-rails-3 - Mongoid,如何通过 references_one 关联(以及后续关联)进行 order_by?

ruby - 将 PDF 内容与 Ruby 进行比较

ruby-on-rails - 我是否正确使用了 rails 表单?

c++ - C++ 中的验证框架