Rails 3.1 Rspec 为模型创建测试用例验证字段 [英] Rails 3.1 Rspec Creating test case validate field for Model
问题描述
我正在尝试为用户模型创建一个测试用例.基本上,它将验证 first_name 和 last_name 是否存在.
I'm trying to create a test case for User model. Basically, it will validate first_name and last_name to be present.
我要做的是检查特定字段上的错误是否为空,并且应该为空.但是它总是失败.
What I am trying to do is to check whether the error on a specific field is empty or not and it should be empty. However it always fails.
这样做的正确方法是什么?
What is the correct way to do this?
这是我的代码
在我的 user_spec.rb 上
On my user_spec.rb
require 'spec_helper'
describe User do
before do
@user = User.new
end
it "must have a first name" do
@user.errors[:first_name].should_not be_empty
end
it "must have a last name" do
@user.errors[:last_name].should_not be_empty
end
end
在我的 user.rb 文件中
On my user.rb file
class User < ActiveRecord::Base
validates :first_name, :presence => true
validates :last_name, :presence => true
end
推荐答案
RSpec 支持隐式"主题的概念.如果describe"块的第一个参数是一个类,RSpec 会自动使该类的实例可用于您的规范.请参阅 http://relishapp.com/rspec/rspec-core/v/2-6/dir/subject/implicit-subject.
RSpec supports the notion of an "implicit" subject. If your first argument to the "describe" block is a class, RSpec automatically makes an instance of that class available to your specs. See http://relishapp.com/rspec/rspec-core/v/2-6/dir/subject/implicit-subject.
require 'spec_helper'
describe User do
it "must have a first name" do
subject.should have(1).error_on(:first_name)
end
it "must have a last name" do
subject.should have(1).error_on(:last_name)
end
end
导致 RSpec 输出(如果使用 --format 文档):
which results in RSpec output (if using --format documentation) of:
User
must have a first name
must have a last name
如果您对 RSpec 输出默认值感到满意,您可以进一步缩写它:
You can abbreviate it even further if you are content with the RSpec output defaults:
require 'spec_helper'
describe User do
it { should have(1).error_on(:first_name) }
it { should have(1).error_on(:last_name) }
end
导致:
User
should have 1 error on :first_name
should have 1 error on :last_name
这篇关于Rails 3.1 Rspec 为模型创建测试用例验证字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!