Tuesday, April 10, 2012

How to test Rspec in controller

In controller,


def admin_search
    @admins = User.find(:all,:joins=>[:roles],:conditions=>["name IN (?) and email like '#{params[:email]}%'",["content team","ops team"]]).paginate(:page => params[:page], :per_page => 10)
 end
 


please suggest me some code in rspec



Answer:


First of all, it's better to extract find(:all, ...) call to User model. Call it search, for instance.
class User < ActiveRecord::Base
  scope :search_by_email, lambda { |email|
    joins(:roles).where(["name IN (?) and email like '#{email}%'",["content team","ops team"]])
  }
end
Use it in the controller then:
def admin_search
   @admins = User.search_by_email(params[:email]).paginate(:page => params[:page], :per_page => 10)
end
Now, you can test the search_by_email method in isolation - check, that it returns result for "content team" and "ops team" only, correctly works with empty email string and so on.
I don't think you have to test paginate method, as it should be already tested in kaminari, will_paginate or whatever you use. But if you want to be sure, that it is being called, than you can use mock expectations (should_receive) in the controller specs.
EDIT: How the specs could look like
describe User do
  describe ".search_by_email" do
    let(:content_team) { Role.create! name: "content team" }
    let(:ops_team)     { Role.create! name: "ops team"     }
    let(:another_team) { Role.create! name: "another team" }

    it "should search in content team" do
      content_team_user = User.create! email: "joe.black@example.com", roles: [content_team]
      User.search_by_email("black").should == [content_team_user]
    end

    it "should search in ops team" do
      ops_team_user = User.create! email: "joe.black@example.com", roles: [ops_team]
      User.search_by_email("black").should == [ops_team_user]
    end

    it "should not search in other teams" do
      other_team_user = User.create! email: "joe.black@example.com", roles: [another_team]
      User.search_by_email("black").should == []
    end

    it "should not search by empty string" do
      content_team_user = User.create! email: "joe.black@example.com", roles: [content_team_user]
      User.search_by_email("").should == []
      User.search_by_email(nil).should == []
    end

    # more specs for search...
  end
end


describe UsersController do
  describe "admin search" do
    let(:admin_user) { double(:admin_user).as_null_object }
    let(:search_string) { 'joe' }

    it "should search for admin users" do
      User.should_receive(:search_by_email).with(search_string).and_return([admin_user])
      get :admin_search, email: search_string
      assigns(:admins).should == [admin_user]
    end
  end
end

No comments:

Post a Comment