Rails 3.1 Rspec Creating a Test Field Validation Field for a Model

I am trying to create a test case for the User model. Basically, it will check first_name and last_name.

I am trying to check if an error in a specific field is empty or not, and it should be empty. However, he always fails.

What is the right way to do this?

Here is my code

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 

In user.rb file

 class User < ActiveRecord::Base validates :first_name, :presence => true validates :last_name, :presence => true end 
+4
source share
2 answers

RSpec supports the concept 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 specifications. 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 

which leads to the conclusion of RSpec (if - format documentation is used):

 User must have a first name must have a last name 

You can reduce it even further if you are happy with the default RSpec output options:

 require 'spec_helper' describe User do it { should have(1).error_on(:first_name) } it { should have(1).error_on(:last_name) } end 

that leads to:

 User should have 1 error on :first_name should have 1 error on :last_name 
+16
source

You can test just by doing this:

 describe 'validations' do it { should validate_presence_of :firstname } it { should validate_presence_of :lastname } end 

Take a look at the helper sockets for all of these standard Rails checks. This method is not only more concise, but also takes care of a positive case. This means that you do not need to test the script mentioned below:

 it "passed validations when first_name is set" user = User.create(:firstname => 'f', :lastname => 'l') user.errors[:first_name].should be_empty user.errors[:last_name].should be_empty end 
+18
source

All Articles