使用.new或.create!使用 Rspec 测试 Rails 模型时?
我在 Rails 3.1 应用程序中有一个联系人表。我希望 last_name 接受 40 个字符,因此在我的模型中我编写了 :length =>; {:最大=> 40}
。然而,我的迁移中的一个拼写错误创建了带有 :limit => 的 last_name 列。 30。
我想知道为什么我的 Rspec 测试没有发现这一点:
it "should allow last_name up to max length" do
long_field = "a" * 40
Contact.new(@attr.merge(:last_name => long_field)).should be_valid
end
然后我意识到这只是检查模型。如果我使用 .create!
代替,测试就会失败:
it "should allow last_name up to max length" do
long_field = "a" * 40
Contact.create!(@attr.merge(:last_name => long_field)).should be_valid
end
所以问题是,在测试模型时我应该始终使用 .create!
吗?还是那太慢了?我还能如何确保我的模型和数据库定义不冲突?
这也让我想知道是否应该在数据库中将字符串保留为 255,并且只检查模型中的长度。
I have a Contacts table in a Rails 3.1 app. I want last_name to accept 40 characters, so in my model I wrote :length => { :maximum => 40 }
. However a typo in my migration created the last_name column with :limit => 30
.
I wondered why my Rspec test hadn't caught this:
it "should allow last_name up to max length" do
long_field = "a" * 40
Contact.new(@attr.merge(:last_name => long_field)).should be_valid
end
then I realized that's only checking the model. If I use .create!
instead, the test fails nicely:
it "should allow last_name up to max length" do
long_field = "a" * 40
Contact.create!(@attr.merge(:last_name => long_field)).should be_valid
end
So the question is, should I always use .create!
when testing my models? Or is that too slow? How else can I make sure that my model and DB definitions don't conflict?
This also has me wondering if I should just leave strings as 255 in the database and only check the length in the model.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
出于速度原因,您应该尽可能多地使用 .new。为了让你的测试失败,你应该使用 validates_length_of。至于字符串长度,理想情况下它们应该匹配,如果您感觉过于彻底,您可以 反映验证和 Model.columns 以验证您是否对每列进行了验证。
You should use .new as much as possible for speed reasons. And to make your test fail you should use validates_length_of. As for the string length, ideally they should match and if you are feeling excessively thorough you could reflect on validations and Model.columns to verify that you have validation for each column.