如何使用 RSpec 在 Rails 中测试包含验证 [英] How can I test :inclusion validation in Rails using RSpec

查看:45
本文介绍了如何使用 RSpec 在 Rails 中测试包含验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 ActiveRecord 中有以下验证.

I have the following validation in my ActiveRecord.

validates :active, :inclusion => {:in => ['Y', 'N']}

我正在使用以下内容来测试我的模型验证.

I am using the following to test my model validations.

should_not allow_value('A').for(:active)
should allow_value('Y').for(:active)
should allow_value('N').for(:active)

是否有更清洁、更彻底的测试方式?我目前正在使用 RSpec2 和 shoulda 匹配器.

Is there a cleaner and more through way of testing this? I am currently using RSpec2 and shoulda matchers.

编辑

环顾四周后,我才发现,这可能是一种不错"的测试方式,应该不为此提供任何东西,任何需要它的人都可以为它编写自己的自定义匹配器.(并且可能将其贡献回给该项目).一些可能有趣的讨论链接:

After some looking around I only found, this probably an 'ok' way of testing this, shoulda does not provide anything for this and anyone who requires it can write their own custom matcher for it.(And probably contribute it back to the project). Some links to discussions that might be intresting:

should_ensure_value_in_range 这个接近可以使用的,但只接受范围而不是值列表.自定义匹配器可以基于此.

should_ensure_value_in_range This one comes close to what can be used, but only accepts ranges and not a list of values. Custom matcher can be based on this.

推荐答案

使用 shoulda_matchers

shouda-matchers 的最新版本中(至少从 v2.7.0 开始),您可以:

Use shoulda_matchers

In recent versions of shoulda-matchers (at least as of v2.7.0), you can do:

expect(subject).to validate_inclusion_of(:active).in_array(%w[Y N])

这会测试验证中可接受值的数组是否与此规范完全匹配.

This tests that the array of acceptable values in the validation exactly matches this spec.

在早期版本中, >= v1.4 ,should_matchers 支持这种语法:

In earlier versions, >= v1.4 , shoulda_matchers supports this syntax:

it {should ensure_inclusion_of(:active).in_array(%w[Y N]) }

这篇关于如何使用 RSpec 在 Rails 中测试包含验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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