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 }

もう 1 つの可能性は、以前に別のフィルターが原因でリダイレクトされていることです。たとえば、ActiveRecord::NotFound の場合にリダイレクトするフィルターです。問題を特定するまで、モック/期待を実際の呼び出しに置き換えることをお勧めします。

また、Devise、特に Devise::TestHelpers#sign_in を参照して、認証テストのインスピレーションを得ることもできます。

于 2012-04-16T16:35:00.267 に答える