Rspec没有登录用户进行测试

时间:2012-04-16 16:12:19

标签: ruby-on-rails rspec

我正在尝试测试控制器的'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

这是我的spec文件

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登录用户?

1 个答案:

答案 0 :(得分:0)

我不清楚#authenticate_user是什么!正在做,但我的猜测是你在一些认证的顶部嘲笑:

controller.stub_chain(:current_user, :templates, :build) { template }

另一种可能性是由于之前的另一个过滤器而被重定向,例如,如果ActiveRecord :: NotFound重定向的过滤器。我建议用真实的电话取代模拟/期望,直到你找出问题为止。

你也可以看看Devise,特别是Devise :: TestHelpers#sign_in,以获得认证测试的灵感。