我正在尝试测试我的控制器的“CREATE”方法以在成功时重定向到 root_url。
# 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 登录用户?