2

我仍在尝试找出 rspec,现在我正在使用 authlogic 来处理我的用户和会话。我做了通常的 authlogic 工作,例如将 def current_user 方法添加到 applciation 控制器,并作为辅助方法,但是如何在我的 rspec 控制器文件中访问它?

这是我的 user_sessions_controller_spec.rb:

require 'spec_helper'
require 'authlogic'

describe UserSessionsController do

  context "user is already logged in" do

    before(:each) do
      include Authlogic::TestCase
      activate_authlogic
      UserSession.create Factory.build(:user)
    end

    it "should redirect the user to the home page" do
      get 'new'
      response.should redirect_to(home_path)
    end

  end

  describe "#create" do
    context "when the user is not logged in" do    
      before(:each) do
        current_user = nil
      end

      it "correct authorization should create a new session" do
        post 'create', {:login => "afactoryuser", :password => "apass", :password_confirmation => "apass"}
        current_user.should_not be_nil
      end
    end
  end

end

当我运行 rspec 它只是告诉我:

correct authorization should create a new session
undefined local variable or method `current_user' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_2::Nested_1:0x000001017d3410>

所以我猜它在 rspec 上下文中......但我怎么知道它应该在 user-sessions_controller 中?我什至可以正确测试它吗?

4

1 回答 1

3

Insted of current_user in your RSpec, try controller.current_user

If you want to stub current_user method use: controller.stub!(:current_user).and_return(whatever) in before :each block, but then you will always get whatever if you stub it.

于 2011-01-19T17:54:14.940 回答