我正在编写一个用户可以在其中填写邮政编码的应用程序。在荷兰,邮政编码的格式是数字的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个字母
发布评论