use*_*082 2 rspec ruby-on-rails
我在寻找最优雅的方法来测试模型中属性的范围时遇到了一些麻烦。我的模型看起来像:
class Entry < ActiveRecord::Base
attr_accessible :hours
validates :hours, presence: true,
:numericality => { :greater_than => 0, :less_than => 24 }
end
Run Code Online (Sandbox Code Playgroud)
我的 rspec 测试如下所示:
require 'spec_helper'
describe Entry do
let(:entry) { FactoryGirl.create(:entry) }
subject { entry }
it { should respond_to(:hours) }
it { should validate_presence_of(:hours) }
it { should validate_numericality_of(:hours) }
it { should_not allow_value(-0.01).for(:hours) }
it { should_not allow_value(0).for(:hours) }
it { should_not allow_value(24).for(:hours) }
# is there a better way to test this range?
end
Run Code Online (Sandbox Code Playgroud)
这个测试有效,但是有没有更好的方法来测试最小值和最大值?我的方法看起来很笨拙。测试值的长度似乎很容易,但我不知道如何测试数字的值。我尝试过这样的事情:
it { should ensure_inclusion_of(:hours).in_range(0..24) }
Run Code Online (Sandbox Code Playgroud)
但这预计会出现包含错误,并且我无法让我的测试通过。也许我配置不正确?
我最终在两个边界处、上方和下方进行了测试,如下所示。因为我不限制整数,所以我测试到小数点后两位。我认为这对于我的应用程序来说可能“足够好”。
it { should_not allow_value(-0.01).for(:hours) }
it { should_not allow_value(0).for(:hours) }
it { should allow_value(0.01).for(:hours) }
it { should allow_value(23.99).for(:hours) }
it { should_not allow_value(24).for(:hours) }
it { should_not allow_value(24.01).for(:hours) }
Run Code Online (Sandbox Code Playgroud)
您正在寻找的 should 匹配器是 is_greater_than 和 is_less_than 匹配器。它们可以链接到 validate_numericality_of 匹配器,如下所示
it {should validate_numericality_of(:hours).is_greater_than(0).is_less_than(24)}
Run Code Online (Sandbox Code Playgroud)
这将验证您的范围内的数字是否会产生有效的变量,并且对于超出该范围的数字返回的错误是否正确。您是正确的,ensure_inclusion_of 匹配器不起作用,因为它期待不同类型的错误,但此验证应该可以正常工作。
| 归档时间: |
|
| 查看次数: |
7181 次 |
| 最近记录: |