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?
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
On my user.rb file
class User < ActiveRecord::Base
validates :first_name, :presence => true
validates :last_name, :presence => true
end
You can test by simply doing this as well:
Take a look at the shoulda matchers for all such standard Rails Validation. This way is not just more concise but also takes care of the positive case. Meaning you then dont need to test the scenario mentioned below:
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.
which results in RSpec output (if using --format documentation) of:
You can abbreviate it even further if you are content with the RSpec output defaults:
which results in: