是否有针对属性的确切长度的rspec测试?

时间:2013-04-19 21:34:11

标签: rspec tdd bdd

我正在尝试测试邮政编码属性的长度,以确保其长度为5个字符。现在我正在测试,以确保它不是空白,然后太短,4个字符,太长,6个字符。

有没有办法测试它正好是5个字符?到目前为止,我没有在网上或在rspec书中找到任何内容。

5 个答案:

答案 0 :(得分:17)

RSpec的最新主要版本中不再有have匹配器。

从RSpec 3.1开始,正确的测试方法是:

expect("Some string".length).to be(11)

答案 1 :(得分:15)

RSpec允许这样:

expect("this string").to have(5).characters

你实际上可以写任何东西而不是'字符',它只是语法糖。所有发生的事情都是RSpec正在调用#length这个主题。

然而,从您的问题来看,您实际上想要测试验证,在这种情况下,我会按照@ rossta的建议进行操作。

更新:

自RSpec 3以来,这不再是rspec期望的一部分,而是作为一个独立的宝石提供:https://github.com/rspec/rspec-collection_matchers

答案 2 :(得分:3)

使用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

答案 3 :(得分:2)

如果您正在测试ActiveRecord模型的验证,我建议您尝试shoulda-matchers。它提供了许多对Rails有用的有用的RSpec扩展。您可以为您的邮政编码属性编写简单的一行规范:

describe Address do
  it { should ensure_length_of(:zip_code).is_equal_to(5).with_message(/invalid/) }
end

答案 4 :(得分:1)

集合匹配器(所有对字符串,散列和数组断言的匹配器)已被抽象为单独的宝石rspec-collection_matchers

要使用这些匹配器,请将其添加到Gemfile

gem 'rspec-collection_matchers'

如果您正在处理某个宝石,请使用.gemspec

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

请注意,您可以互换使用itemscharacters,它们只是syntax-sugar,而have匹配器及其变体可用于数组,哈希和你的字符串。