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

gr0*_*r0k 12 tdd bdd rspec

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

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

Pak*_*Pak 18

haveRSpec的最新主要版本中没有更多的匹配器.

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

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


And*_*ite 16

RSpec允许这样:

expect("this string").to have(5).characters
Run Code Online (Sandbox Code Playgroud)

你实际上可以写任何东西而不是'字符',它只是语法糖.发生的一切都是RSpec呼吁#length这个话题.

但是,从您的问题来看,听起来您确实想要测试验证,在这种情况下,我会接受@ rossta的建议.

更新:

因为RSpec的3,这是rspec的期许不再一部分,但可以作为一个独立的宝石:https://github.com/rspec/rspec-collection_matchers


ska*_*lee 14

使用have_attributes内置匹配器:

expect("90210").to have_attributes(size: 5) # passes
expect([1, 2, 3]).to have_attributes(size: 3) # passes
Run Code Online (Sandbox Code Playgroud)

您还可以将其与其他匹配器组合(此处为be):

expect("abc").to have_attributes(size: (be > 2)) # passes
expect("abc").to have_attributes(size: (be > 2) & (be <= 4)) # passes
Run Code Online (Sandbox Code Playgroud)


ros*_*sta 2

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

describe Address do
  it { should ensure_length_of(:zip_code).is_equal_to(5).with_message(/invalid/) }
end
Run Code Online (Sandbox Code Playgroud)