如何检查rspec中是否存在辅助方法/变量?

时间:2011-01-06 07:09:32

标签: authlogic rspec2

我仍然试图找出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中?我是否正确测试它?

1 个答案:

答案 0 :(得分:3)

而不是RSpec中的current_user,请尝试controller.current_user

如果你想在[{1}}块中使用:controller.stub!(:current_user).and_return(whatever),那么你可以在before :each块中使用whatever,但如果你将它存在,你将永远得到{{1}}。