0

我正在尝试测试我的控制器的“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 登录用户?

4

1 回答 1

0

我不完全清楚#authenticate_user 是什么!正在做,但我的猜测是你在某些部分的身份验证之上嘲弄:

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

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

您还可以查看 Devise,特别是 Devise::TestHelpers#sign_in,以获取有关身份验证测试的灵感。

于 2012-04-16T16:35:00.267 回答