如何在控制器中测试Rspec

时间:2012-04-10 12:35:30

标签: ruby-on-rails rspec

在控制器中,

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

请在rspec中建议我一些代码

1 个答案:

答案 0 :(得分:3)

首先,最好提取find(:all, ...)对用户模型的调用。例如,将其称为search

class User < ActiveRecord::Base
  scope :search_by_email, lambda { |email|
    joins(:roles).where(["name IN (?) and email like '#{email}%'",["content team","ops team"]])
  }
end

然后在控制器中使用它:

def admin_search
   @admins = User.search_by_email(params[:email]).paginate(:page => params[:page], :per_page => 10)
end

现在,您可以单独测试search_by_email方法 - 检查,它返回&#34;内容团队的结果&#34;和&#34;运营团队&#34;只有,正确使用空电子邮件字符串等等。

我不认为你必须测试paginate方法,因为它应该已经在kaminari,will_paginate或你使用的任何东西中测试过。但是如果你想确定它被调用,那么你可以在控制器规范中使用模拟期望值(should_receive)。

编辑:规格的外观如何

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