我已經完成了第8章的第一部分,只有與這些2個錯誤打招呼:Ruby on Rails的教程章8.1.5未定義的方法 'find_by'
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
我開始研究,通過放入各種片段的錯誤,並通讀類似的問題,並嘗試了他們的解決方案,但無濟於事。即使盯着代碼,我發現問題在於session控制器內部的create方法,特別是find_by方法。對於rails及其概念相當陌生,我仍然感到困惑。任何幫助和解釋將不勝感激。
謝謝因爲它有效,但我仍然有一個呃ror:'失敗/錯誤:it {should have_title('Sign in')} NoMethodError: 未定義的方法'has_title?'對於#'問題在於行內** it {should have_title('Sign in')} **。我檢查了我的new.html.erb,它確實有標題。我注意到該行並通過了測試。但是我希望測試能夠通過而不用評論這些線。請你的想法? –