Ruby on Rails教程第8.1.5章未定义的方法'find_by'

时间:2013-08-06 13:58:17

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

我已经完成了第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)>'

所需文件:

sessions_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方法。作为铁杆及其概念的新手,我仍然感到困惑。任何帮助和解释将不胜感激。

2 个答案:

答案 0 :(得分:0)

这应该做:

user = User.find_by_email(params[:session][:email].downcase)

答案 1 :(得分:0)

我认为您使用的是较旧版本的rails

对于Rails 4

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

对于旧版本,请尝试

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