【发布时间】:2013-04-19 21:34:11
【问题描述】:
我正在尝试测试邮政编码属性的长度,以确保其长度为 5 个字符。现在我正在测试以确保它不是空白,然后太短了 4 个字符,太长了 6 个字符。
有没有办法测试它正好是 5 个字符?到目前为止,我在网上或 rspec 书中都没有找到任何东西。
【问题讨论】:
我正在尝试测试邮政编码属性的长度,以确保其长度为 5 个字符。现在我正在测试以确保它不是空白,然后太短了 4 个字符,太长了 6 个字符。
有没有办法测试它正好是 5 个字符?到目前为止,我在网上或 rspec 书中都没有找到任何东西。
【问题讨论】:
RSpec 的最新主要版本中不再有 have 匹配器。
从 RSpec 3.1 开始,正确的测试方法是:
expect("Some string".length).to be(11)
【讨论】:
RSpec 允许这样做:
expect("this string").to have(5).characters
您实际上可以写任何东西来代替“字符”,它只是语法糖。正在发生的一切是 RSpec 正在就该主题调用 #length。
但是,从您的问题来看,您实际上想测试验证,在这种情况下,我会听从@rossta 的建议。
更新:
自 RSpec 3 起,这不再是 rspec-expectations 的一部分,而是作为单独的 gem 提供:https://github.com/rspec/rspec-collection_matchers
【讨论】:
使用have_attributes内置匹配器:
expect("90210").to have_attributes(size: 5) # passes
expect([1, 2, 3]).to have_attributes(size: 3) # passes
你也可以compose it with other matchers(这里用be):
expect("abc").to have_attributes(size: (be > 2)) # passes
expect("abc").to have_attributes(size: (be > 2) & (be <= 4)) # passes
【讨论】:
如果您在 ActiveRecord 模型上测试验证,我建议您尝试shoulda-matchers。它提供了一堆对 Rails 有用的 RSpec 扩展。您可以为您的邮政编码属性编写一个简单的一行规范:
describe Address do
it { should ensure_length_of(:zip_code).is_equal_to(5).with_message(/invalid/) }
end
【讨论】:
集合匹配器(所有针对字符串、哈希和数组断言的匹配器)已被抽象为一个单独的 gem,rspec-collection_matchers。
为了使用这些匹配器,请将其添加到您的Gemfile:
gem 'rspec-collection_matchers'
或者你的.gemspec,如果你正在研究一个gem:
spec.add_development_dependency 'rspec-collection_matchers'
然后,将此添加到您的spec_helper.rb:
require 'rspec/collection_matchers'
然后你就可以在你的规范中使用集合匹配器了:
require spec_helper
describe 'array' do
subject { [1,2,3] }
it { is_expected.to have(3).items }
it { is_expected.to_not have(2).items }
it { is_expected.to_not have(4).items }
it { is_expected.to have_exactly(3).items }
it { is_expected.to_not have_exactly(2).items }
it { is_expected.to_not have_exactly(4).items }
it { is_expected.to have_at_least(2).items }
it { is_expected.to have_at_most(4).items }
# deliberate failures
it { is_expected.to_not have(3).items }
it { is_expected.to have(2).items }
it { is_expected.to have(4).items }
it { is_expected.to_not have_exactly(3).items }
it { is_expected.to have_exactly(2).items }
it { is_expected.to have_exactly(4).items }
it { is_expected.to have_at_least(4).items }
it { is_expected.to have_at_most(2).items }
end
请注意,您可以交替使用 items 和 characters,它们只是语法糖,have 匹配器及其变体可用于数组、哈希和您的字符串。
【讨论】: