0

我已经完成了第 8 章的第一部分,却遇到了以下两个错误:

Failures:

  1) Authentication signin with invalid information 
     Failure/Error: before { click_button "Sign in" }
     NoMethodError:
       undefined method `find_by' for #<Class:0xab805ec>
     # ./app/controllers/sessions_controller.rb:7:in `create'
     # (eval):2:in `click_button'
     # ./spec/requests/authentication_pages_spec.rb:18:in `block (4 levels) in <top  required)>'

  2) Authentication signin with invalid information 
     Failure/Error: before { click_button "Sign in" }
     NoMethodError:
       undefined method `find_by' for #<Class:0xab805ec>
     # ./app/controllers/sessions_controller.rb:7:in `create'
     # (eval):2:in `click_button'
     # ./spec/requests/authentication_pages_spec.rb:18:in `block (4 levels) in <top (required)>'

所需文件:

session_controller

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      # Sign the user in and redirect to the user's show page.
    else
      flash.now[:error] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
  end
end

身份验证页面规范

require 'spec_helper'

describe "Authentication" do

 subject { page }

 describe "signin page" do
   before { visit signin_path }

   it { should have_content('Sign in') }
   it { should have_title('Sign in') }
 end

 describe "signin" do
   before { visit signin_path }

   describe "with invalid information" do
     before { click_button "Sign in" }

     it { should have_title('Sign in') }
     it { should have_selector('div.alert.alert-error', text: 'Invalid') }
   end

     describe "after visiting another page" do
       before { click_link "Home" }
       it { should_not have_selector('div.alert.alert-error') }
     end
   end

   describe "with valid information" do
     let(:user) { FactoryGirl.create(:user) }
     before do
       fill_in "Email",    with: user.email.upcase
       fill_in "Password", with: user.password
       click_button "Sign in"
    end

    it { should have_title(user.name) }
    it { should have_link('Profile',     href: user_path(user)) }
    it { should have_link('Sign out',    href: signout_path) }
    it { should_not have_link('Sign in', href: signin_path) }
    end

end 

我开始通过输入错误的各种片段进行研究,并阅读了类似的问题并尝试了他们的解决方案,但无济于事。即使盯着代码,我也发现问题与会话控制器中的 create 方法有关,特别是 find_by 方法。对 Rails 及其概念相当陌生,我仍然感到困惑。任何帮助和解释将不胜感激。

4

2 回答 2

0

这应该这样做:

user = User.find_by_email(params[:session][:email].downcase)
于 2013-08-06T13:59:57.030 回答
0

我认为您使用的是旧版本的导轨

对于 Rails 4

User.find_by(email: params[:session][:email].downcase)

对于旧版本尝试

User.find_by_email(params[:session][:email].downcase) 
于 2013-08-06T14:00:27.250 回答