[英]How to test Rspec in controller
In controller,在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请在 rspec 中建议我一些代码
First of all, it's better to extract find(:all, ...)
call to User model. Call it search
, for instance.首先,最好提取对用户 model 的
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
Use it in the controller then:然后在 controller 中使用它:
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.现在,您可以单独测试
search_by_email
方法 - 检查它是否仅返回“content team”和“ops team”的结果,正确处理空 email 字符串等。
I don't think you have to test paginate
method, as it should be already tested in kaminari, will_paginate or whatever you use.我认为您不必测试
paginate
方法,因为它应该已经在 kaminari、will_paginate 或任何您使用的方法中进行了测试。 But if you want to be sure, that it is being called, than you can use mock expectations ( should_receive
) in the controller specs.但是如果你想确定它正在被调用,那么你可以在 controller 规范中使用模拟期望(
should_receive
)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.