Rails + Rspec。 Michael Hartl教程。实现sign_in

时间:2014-03-07 23:44:14

标签: ruby-on-rails ruby ruby-on-rails-3 rspec

我收到此错误但无法找到该功能,但我无法理解原因。这是我的代码:

  

session_helper.rb

  def sign_in(user)
    cookies.permanent.signed[:remember_token] = [user.id, user.salt]
    current_user = user
  end
...
...
  

session_controller.rb

  def create
    user = User.authenticate(params[:session][:email], params[:session][:password])
    if user.nil?
      flash.now[:error] = "Invalid email/password combination"
      @title = "Sign in"
      render 'new'
    else
      sign_in(user)
      redirect_to user
    end
  end
  

sessions_controller_spec.rb

    it "should sign the user in" do 
      post :create, session: @attr
      expect(controller.current_user).to eq @user
      expect(controller).to be_signed_in
    end

    it "should redirect to the user show page" do 
      post :create, session: @attr
      expect(response).to redirect_to(user_path(@user))
    end
  

Rspec的

  2) SessionsController success should redirect to the user show page
     Failure/Error: post :create, session: @attr
     NoMethodError:
     undefined method `sign_in' for #<SessionsController:0x00000006409380>

如果我把函数sign_in放在sessions_controller中我没有得到这个错误但是如果我把函数保留在帮助器中我的程序就是看不到该函数。为什么呢?

2 个答案:

答案 0 :(得分:1)

include SessionsHelperApplicationController中的

SessionsController。 辅助方法无法在控制器中直接访问。你需要包括它们。

答案 1 :(得分:-1)

您应该包含帮助程序模块。将其添加到spec_helper.rb

RSpec.configure do |config|
  ...
  config.include SessionHelper #add this line
  ...
end