urjit on rails
urjit on rails

Reputation: 1893

Rspec controller spec

I am new to Rspec please tell me what would be the controller Spec for the following two methods In index method only login page is seen by entering the username control goes to login method and find the name of person. If person is find then control goes to people path otherwise it goes back to root path that is index page it self.

class HomeController < ApplicationController
def index

end

def login
  @person = Person.find(:all, :conditions => ['people.name =?', params[:person][:name]] )

  if @person.blank?
    redirect_to root_path          
  else
    redirect_to people_path
  end
end
end

Please help me.
Thanks.

Upvotes: 2

Views: 2673

Answers (1)

Salil
Salil

Reputation: 9722

Your rspec controller tests could be like this:

describe HomeController do
  render_views
  it "Logs in Person with non-blank name" do
    person = Factory(:Person, name: "non-blank name")
    get :login
    response.should redirect_to(people_path)
  end
  it "does not log in Person with blank name" do
    person = Factory(:Person, name: "") # blank name
    get :login
    response.should redirect_to(root_path)
  end
end

Refer to rails controller specs for details.

EDIT:

Factory: the code that creates objects (test objects in this case). This is a preferred method for creating test objects because you can customize your code to create objects with varying attributes with least duplication.

Fixtures: If you are not using factories, you can specify the attributes for each of the objects you are going to create. For more than 2-3 object, this data quickly becomes unmanageable to maintain (for example, when you add an attribute, you need to make changes for each of these objects).

Stubs: If you prefer not to create database records while creating model objects, you can stub the model code white testing controllers.

For more information, refer:
1. testing guide
2. asciicast (Note: this code refers to an older version of FactoryGirl gem. Refer below for up-to-date API of FactoryGirl)
3. FactoryGirl Readme

Upvotes: 5

Related Questions