Rspec:当模型无效时显示模型的错误 [英] Rspec: Show a model's errors when it's not valid

查看:48
本文介绍了Rspec:当模型无效时显示模型的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常在我的 Rspec 测试中写这样的东西:

I generally write something like this in my Rspec tests:

user.new(...)
user.should be_valid

问题是,当测试失败时,我看不到用户对象上的错误.有没有一种很好的方法来重新编写这个测试,以便在 Rspec 输出中我会看到类似 user.errors.inspect 的内容?我已经尝试了 user.errors.should be_empty,但这仍然只是说预期为真,得到了假."

The problem is, when that test fails, I don't get to see the errors on the user object. Is there a nice way to re-write this test so that in the Rspec output I'll see something like user.errors.inspect? I've tried user.errors.should be_empty, but that still just says "expected true, got false."

推荐答案

您可以通过定义自定义匹配器来实现此目的.像这样的事情应该可以解决问题.

You can do this by defining a custom matcher. Something like this should do the trick.

RSpec::Matchers.define :be_valid do
  match do |actual|
    actual.valid?
  end

  failure_message_for_should do |actual|
    "expected that #{actual} would be valid (errors: #{actual.errors.full_messages.inspect})"
  end

  failure_message_for_should_not do |actual|
    "expected that #{actual} would not be valid"
  end

  description do
    "be valid"
  end
end

这篇关于Rspec:当模型无效时显示模型的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆