Search code examples
ruby-on-railsdevisetddfactory-botrspec-rails

Understand Test-Driven Development with Rspec and FactoryGirl


Here is my Spec file:

require 'spec_helper'

describe User, "references" do
  it { should have_and_belong_to_many(:roles) }
  it { should belong_to(:account_type) }
  it { should belong_to(:primary_sport).class_name("Sport") }
  it { should belong_to(:school) }
  it { should belong_to(:city) }
end 

describe User, "factory" do
  before(:each) do
    @user = FactoryGirl.create(:user)
  end

  it "is invalid with no email" do
    @user.email = nil
    @user.should_not be_valid
  end

  it "is valid with email" do
    @user.should be_valid
  end
end

Factory:

FactoryGirl.define do
  factory :user do
    email Faker::Internet.email
    password "password"
    password_confirmation "password"
    agreed_to_age_requirements true
  end 
end

The part I am trying to "test" for and not sure how to 100% is checking to make sure when a User is created that the email address is not nil.


Solution

  • shoulda provides validation helpers to help you test the validations.

    it { should validate_presence_of(:email) }
    

    If you want to use rspec and write your own, then

    describe User do
      it "should be invalid without email" do
        user = FactoryGirl.build(:user, :email => nil)
        @user.should_not be_valid
        @user.errors.on(:email).should == 'can't be blank' #not sure about the exact message. But you will know when you run the test
      end
    
      it "should be valid with email" do
        user = FactoryGirl.build(:user, :email => "[email protected]")
        @user.should be_valid
      end
    end
    

    When you run the test, it would read as

    User
      should be invalid without email
      should be valid with email
    

    Giving a good description for your test case is very important, because it kind of acts like a documentation.