Rails 3.1、RSpec:测试模型验证 [英] Rails 3.1, RSpec: testing model validations
问题描述
我在 Rails 中开始了 TDD 之旅,但遇到了一个关于模型验证测试的小问题,我似乎无法找到解决方案.假设我有一个 User 模型,
I have started my journey with TDD in Rails and have run into a small issue regarding tests for model validations that I can't seem to find a solution to. Let's say I have a User model,
class User < ActiveRecord::Base
validates :username, :presence => true
end
和一个简单的测试
it "should require a username" do
User.new(:username => "").should_not be_valid
end
这正确地测试了存在验证,但是如果我想更具体怎么办?例如,在错误对象上测试 full_messages..
This correctly tests the presence validation, but what if I want to be more specific? For example, testing full_messages on the errors object..
it "should require a username" do
user = User.create(:username => "")
user.errors[:username].should ~= /can't be blank/
end
我对初始尝试(使用 should_not be_valid)的担忧是 RSpec 不会产生描述性错误消息.它只是说预期有效?返回假,得到真."但是,第二个测试示例有一个小缺点:它使用 create 方法而不是 new 方法来获取错误对象.
My concern about the initial attempt (using should_not be_valid) is that RSpec won't produce a descriptive error message. It simply says "expected valid? to return false, got true." However, the second test example has a minor drawback: it uses the create method instead of the new method in order to get at the errors object.
我希望我的测试更具体地说明他们正在测试的内容,但同时又不必涉及数据库.
I would like my tests to be more specific about what they're testing, but at the same time not have to touch a database.
有人有任何意见吗?
推荐答案
恭喜您通过 ROR 致力于 TDD,我保证一旦您开始,您将不会回头.
CONGRATULATIONS on you endeavor into TDD with ROR I promise once you get going you will not look back.
最简单的快速和肮脏的解决方案是在每次测试之前生成一个新的有效模型,如下所示:
The simplest quick and dirty solution will be to generate a new valid model before each of your tests like this:
before(:each) do
@user = User.new
@user.username = "a valid username"
end
但我建议您为所有模型设置工厂,这些工厂将自动为您生成有效模型,然后您可以混淆单个属性并查看您的验证.我喜欢使用 FactoryGirl:
BUT what I suggest is you set up factories for all your models that will generate a valid model for you automatically and then you can muddle with individual attributes and see if your validation. I like to use FactoryGirl for this:
基本上,一旦你设置好你的测试就会看起来像这样:
Basically once you get set up your test would look something like this:
it "should have valid factory" do
FactoryGirl.build(:user).should be_valid
end
it "should require a username" do
FactoryGirl.build(:user, :username => "").should_not be_valid
end
哦,是的,这里是 一个很好的 railscast 可以更好地解释这一切比我:
Oh ya and here is a good railscast that explains it all better than me:
祝你好运:)
更新:从 3.0 版起 工厂女孩的语法已更改.我已经修改了我的示例代码以反映这一点.
UPDATE: As of version 3.0 the syntax for factory girl has changed. I have amended my sample code to reflect this.
这篇关于Rails 3.1、RSpec:测试模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!