1

在控制器中,

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 中的一些代码

4

1 回答 1

2

首先,最好提取find(:all, ...)对 User 模型的调用。例如,称之为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方法 - 检查它是否仅返回“内容团队”和“操作团队”的结果,是否正确使用空电子邮件字符串等等。

我认为您不必测试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
于 2012-04-10T12:58:42.163 回答