Michael Hartl Rails Tutorial - undefined method &#

2019-08-17 17:30发布

问题:

I'm actually stuck on Chapter 9 in Michael Hartl Rails Tutorial : http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#sec-unsuccessful_edits

When I run that command line :

$ bundle exec rspec spec/requests/user_pages_spec.rb -e "edit page"

I have that error :

Failure/Error: sign_in user
NoMethodError: undefined method 'sign_in' for #<RSpec::Core::ExampleGroupe::Nested_1::Nested_4::Nested_1:0x4e7a0b8>

Issue come from this code in spec/requests/user_pages_spec.rb :

describe "edit" do
  let(:user) { FactoryGirl.create(:user) }
  before do
    sign_in user
    visit edit_user_path(user)
  end
end

But sign_in is actually defined in app/helpers/sessions_helper.rb :

def sign_in(user)
  remember_token = User.new_remember_token
  cookies.permanent[:remember_token] = remember_token
  user.update_attribute(:remember_token, User.encrypt(remember_token))
  self.current_user = user
end

def signed_in?
  !current_user.nil?
end

def current_user=(user)
  @current_user = user
end

def current_user
  remember_token = User.encrypt(cookies[:remember_token])
  @current_user ||= User.find_by(remember_token: remember_token)
end

And SessionsHelper is include in app/controllers/application_controller.rb :

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper
end

Do you have a solution?

回答1:

Your user_pages_spec.rb is a test specification. It will need the sign_in method in a test helper, not the helper for the application I'm pretty sure. I did that tutorial a while back, but just reviewed. I think you need to add something to spec/support/utilities.rb that gives it a sign_in method for your specs.

The final answer on Hartl's github repo is:

include ApplicationHelper

def sign_in(user)
  visit signin_path
  fill_in "Email",    with: user.email
  fill_in "Password", with: user.password
  click_button "Sign in"
  # Sign in when not using Capybara as well.
  cookies[:remember_token] = user.remember_token
end

That should be your spec/support/utilities.rb final.

In the tutorial itself, he brings that up in section 9.6.

Listing 9.6. A test helper to sign users in.

spec/support/utilities.rb
.
.
.
def sign_in(user, options={})
  if options[:no_capybara]
    # Sign in when not using Capybara.
    remember_token = User.new_remember_token
    cookies[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.encrypt(remember_token))
  else
    visit signin_path
    fill_in "Email",    with: user.email
    fill_in "Password", with: user.password
    click_button "Sign in"
  end
end

That obviously differs from the final, but, I imagine it is where you need to start.