Formfield在Rspec中应该有4个数字,后跟2个字母

编程入门 行业动态 更新时间:2024-10-24 02:37:35
本文介绍了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个字母

本文发布于:2023-11-16 06:22:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1601777.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后跟   字母   数字   Formfield   Rspec

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!