【问题标题】:Nil value in virtual attribute not caught by Rails validation?Rails验证未捕获虚拟属性中的零值?
【发布时间】:2017-03-30 15:18:37
【问题描述】:

我有这个 Rails 模型:

class Profile < ActiveRecord::Base

  validates :number_format, :inclusion => { :in => ["1,000.00", "1.000,00"] }

  def number_format=(format)
    self.currency_delimiter = format[1]
    self.currency_separator = format[5]
  end

  def number_format
    "1#{currency_delimiter}000#{currency_separator}00"
  end

end

问题是当我用 RSpec 测试它时...

it "is invalid without a number_format" do
  expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)
end

...我收到此错误:

1) 没有 number_format 的配置文件 number_format 无效 失败/错误:expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)

   expected: 1
        got: 0

这怎么可能?

我认为nil 不会得到验证,因为我采用了验证方法。

【问题讨论】:

  • 你的模型真的有属性number_format吗?我只看到一个名称相似的 setter 方法。是否有名为 number_format 的数据库列或具有该名称的方法?
  • 是的,还有一个getter方法。我刚刚在上面添加了它。但是,没有具有该名称的数据库列。

标签: ruby-on-rails ruby validation rspec


【解决方案1】:

FactoryGirl.build 只是初始化一条记录,它不会尝试将记录保存到数据库中,因此不会在记录上调用valid?。如果不调用valid?,实例错误将始终为空。

试试这个:

it "is invalid without a number_format" do
  profile = FactoryGirl.build(:profile, :number_format => nil)

  expect(profile).to_not be_valid # `be_valid` actually calls `valid?`
  expect(profile.errors_on(:number_format).size).to eq(1)
end

【讨论】:

  • 感谢您的帮助。非常感谢。与此同时,我设法弄清楚我上面发布的错误是由我的factories.rb 文件引起的,我没有定义number_format 虚拟属性。我不是 100% 确定,但我认为这就是它的原因。
【解决方案2】:

如果您使用虚拟属性,我认为错误将保存到:base。你应该检查expect(FactoryGirl.build(:profile, :number_format =&gt; nil).errors.size).to eq(1)

【讨论】:

  • 不错的尝试,但不幸的是,它给了我完全相同的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 2023-04-06
  • 2012-07-13
  • 1970-01-01
相关资源
最近更新 更多