Formfield在Rspec中应该有4个数字,后跟2个字母 [英] Formfield should have 4 numbers followed by 2 letters in Rspec

查看:69
本文介绍了Formfield在Rspec中应该有4个数字,后跟2个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个用户可以在其中填写邮政编码的应用程序。在荷兰,邮政编码的格式是数字的4倍,后跟2个字母。例如,1234AB。

I am writing an application where a user could fill in their zipcode. In the Netherlands a zipcode has a format of 4 times a number, followed by 2 letters. For example, 1234AB.

在我的测试中,我到目前为止已经写过:

In my test I have written so far:

before(:each) do
  @zipcode = Zipcode.new
  @zipcode.zipcode = "1234AB"
  @zipcode.house_number = 2
end

it "should have a valid zipcode" do
  @zipcode.zipcode.should_not be_empty
  @zipcode.zipcode.should be_a(String)
  @zipcode.zipcode.length.should == 6
end

我如何编写测试以检查是否存在4数字后跟2个字母?以及我应该如何在代码本身中写出来呢?

How ca I write the test that it checks if there are 4 numbers followed by 2 letters? And how should I write that in code it self?

推荐答案

您将要使用正则表达式(正则表达式)。对于您的示例,这将非常简单:

You will want to use a Regex (regular expression). For your example, it would be quite simple:

/\A[0-9]{4}[A-Z]{2}\z/

表示:行首,数字4次,2

(我知道,如果您不熟悉该概念,这看起来可能并不简单,但请继续阅读它会很快变得清晰起来。我建议您在Ruby上下文中阅读正则表达式,以了解Ruby正则表达式的所有怪癖(如果您还没有的话)。)

(I know this might not look simple if you're not familiar with the concept, but just read up on it and it will become clear very quickly. I recommend to read up on regexes in a Ruby context to know about all the quirks of Ruby regular expressions if you don't already.)

要在规范中使用此正则表达式,我认为您可以使用以下代码:

To use this regex inside your spec, I think you can use the following:

@zipcode.zipcode.should match(/\A[0-9]{4}[A-Z]{2}\z/)

要使用它在模型中实际验证此格式,请使用

To use it to actually validate this format inside your model, use this:

validates :zipcode, format: /\A[0-9]{4}[A-Z]{2}\z/

这篇关于Formfield在Rspec中应该有4个数字,后跟2个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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