rails rspec预计自定义验证失败

时间:2013-02-05 18:01:53

标签: ruby-on-rails rspec rspec-rails

运行我的rspec期望使用自定义验证器时出现此错误。

expect {@ua.save!}.to  raise_error(ActiveRecord::RecordInvalid,'Validation failed: This question is no longer active')

失败
expected ActiveRecord::RecordInvalid with "Validation failed: This question is no longer active", got #<ActiveRecord::RecordInvalid: Validation failed: This question is no longer active.> with backtrace:

这似乎只是我的自定义验证的问题。 看到这个模型:

class UserAnswer < ActiveRecord::Base
  belongs_to :user
  belongs_to :question
  validate :questionIsActive?

  private

  def questionIsActive?
    errors.add(:base, "This question is no longer active.") if !self.question.is_active?
  end
end

使用: Rails 3.2.11 Rspec-rails 2.12.2

1 个答案:

答案 0 :(得分:9)

你有一个错字。在字符串中添加句点:

expect {@ua.save!}.to  raise_error(ActiveRecord::RecordInvalid,'Validation failed: This question is no longer active.')

注意:您目前符合预期:

'验证失败:此问题不再有效'

但需要:

'验证失败:此问题不再有效。'

以便它与您的验证字符串匹配:

'此问题不再有效。'