RSpec 和 ActiveRecord for Rails:如何编写有效的测试
到目前为止,我已经构建了一个简单的 Rails 应用程序,其中包含三个继承自 ActiveRecord 的类。我在测试驱动开发方面有点领先,因为我已经编写了需要测试的类。到目前为止,我编写的测试一切顺利。对象正在创建,属性正在响应,验证都已就位。
当我调用“!”时,问题就开始了。在我的创建方法上,因为现在对象一直被传递到数据库。我的正常验证并没有拦截无效输入,数据库似乎有机会响应刺激。
到目前为止,我在运行测试时收到的错误是:
ActiveRecord::RecordInvalid: 验证失败:商店太长(最多 11 个字符)
我很高兴收到此错误,但想知道如何在测试中更好地计划它。生成上述错误的代码是:
it "should not a accept a department with a shopify shop_id that's over 11 chars" do
long_id = "9" * 12
long_id_department = Department.create!(@attr.merge(:id => [long_id, ""]))
long_id_department.should_not be_valid
end
我认为这一行特别应该采用其他形式: long_id_department.should_not be_valid
希望大家能够阐明该形式应该是什么。
I have built a simple rails app with three classes that inherit from ActiveRecord so far. I am a little bit ahead on my test driven development as I've already written the classes I need to test. Thus far the tests that I've written have all gone well. Objects are being created, attributes are responding, validations are all in place.
The problem begins when I invoke the "!" on my create methods, since now the objects are being passed all the way along to the database. Instead of my normal validations intercepting the invalid inputs it seems the database is being given a chance to respond to the stimulus.
Thus far the error which I've received when running my tests is:
ActiveRecord::RecordInvalid:
Validation failed: Shop is too long (maximum is 11 characters)
I'm glad that I am getting this error but would like to know how to plan for it better in my tests. The code that generates the above error is:
it "should not a accept a department with a shopify shop_id that's over 11 chars" do
long_id = "9" * 12
long_id_department = Department.create!(@attr.merge(:id => [long_id, ""]))
long_id_department.should_not be_valid
end
I presume that this line in particular should assume some other form: long_id_department.should_not be_valid
Hoping you all could shed some light on what that form should be.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
shoulda gem 使测试验证变得轻而易举。最新的 Shoulda 版本是作为 RSpec 的附加组件构建的。
您尝试的特定类型验证的文档是 此处。
您最终会得到如下所示的测试代码。
The shoulda gem makes testing your validations a piece of cake. The more recent shoulda releases are built as an add-on to RSpec.
The documentation for the specific type of validation you're attempting is here.
You'll end up with test code that looks like this.
您需要捕获 create! 引发的异常。正如您所写,异常正在被 rspec 捕获。
should_not be_valid 测试对于 create 来说毫无意义!因为除非对象有效,否则它会抛出异常。
You need to catch the exception being thrown by create!. As you have written it, the exception is being caught by rspec.
The should_not be_valid test is meaningless for create! since it will throw an exception unless the object is valid.