Rspec不记录用户进行测试
问题描述:
我试图在成功时测试我的控制器的'CREATE'方法以重定向到root_url。Rspec不记录用户进行测试
# templates_controller.rb
require 'open-uri'
class TemplatesController < ApplicationController
before_filter :authenticate_user! # Authenticate for users before any methods are called
def create
@template = current_user.templates.build(params[:template])
if @template.save
flash[:notice] = "Successfully uploaded the file."
if @template.folder #checking if we have a parent folder for this file
redirect_to browse_path(@template.folder) #then we redirect to the parent folder
else
redirect_to root_url
end
else
render :action => 'new'
end
end
end
这是我的规格文件
describe "POST 'create'" do
let(:template) { mock_model(Template) }
before(:each) do
controller.stub_chain(:current_user, :templates, :build) { template }
end
context "success" do
before(:each) do
template.should_receive(:save).and_return(true)
post :create
end
it "sets flash[:notice]" do
flash[:notice].should == "Successfully uploaded the file."
end
it "redirects to the root_url" do
response.should redirect_to(root_url)
end
end
end
这是错误,我得到
TemplatesController POST 'create' success sets flash[:notice]
Failure/Error: flash[:notice].should == "Successfully uploaded the file."
expected: "Successfully uploaded the file."
got: nil (using ==)
# ./spec/controllers/templates_controller_spec.rb:35:in `block (4 levels) in <top (required)>'
12) TemplatesController POST 'create' success redirects to the root_url
Failure/Error: response.should redirect_to(root_url)
Expected response to be a redirect to <http://test.host/> but was a redirect to <http://test.host/users/sign_in>
# ./spec/controllers/templates_controller_spec.rb:39:in `block (4 levels) in <top (required)>'
13) Template should be valid
Failure/Error: Template.new.should be_valid
expected valid? to return true, got false
# ./spec/models/template_spec.rb:5:in `block (2 levels) in <top (required)>'
试验显然没有登录,因为它重定向到http://test.host/users/sign_in用户。我如何获得rspec来登录用户?
答
我不完全清楚什么#authenticate_user!是干什么的,但我的猜测是你的嘲弄与以上认证的某一部分的顶部:
controller.stub_chain(:current_user, :templates, :build) { template }
另一种可能是你正在因为另一个过滤器更早重定向,例如重定向如果ActiveRecord的过滤器:: NOTFOUND 。我建议用真正的电话代替嘲笑/期望,直到你找出问题。
您也可以看看Devise,特别是Devise :: TestHelpers#sign_in,以获取身份验证测试的灵感。
什么是我可以使用的一些例子,而不是嘲笑/期望? – RubyNerd 2012-04-16 18:15:46
尝试插入您为测试创建的规格#authenticate_user !,即实际发布到控制器的真实身份验证数据以将测试用户记入日志 – 2012-04-17 17:19:56