运行Integration Test的NoMethodError,RailsTutorial Ch9

时间:2018-06-02 23:28:13

标签: ruby-on-rails-5 railstutorial.org

我遇到的问题是我的集成测试似乎没有找到test_helper.rb中的log_in_as方法

我一直在关注迈克尔哈特的Rails教程,所以我希望不要大规模重构我的代码来尝试让它工作。我想继续阅读这本书而不必排除测试,因为它毕竟是非常考验的。

错误:

UsersLoginTest#test_login_with_remembering:
NoMethodError: undefined method `log_in_as' for #<UsersLoginTest:0x00000005b18460>
    test/integration/users_login_test.rb:43:in `block in <class:UsersLoginTest>'

User_login_test.rb:

require 'test_helper.rb'

class UsersLoginTest < ActionDispatch::IntegrationTest

.
.
.

  test "login with remembering" do
    log_in_as(@user, remember_me: '1')
    assert_not_empty cookies['remember_token']
  end

  test "login without remembering" do
    # Log in to set the cookie.
    log_in_as(@user, remember_me: '1')
    # Log in again and verify that the cookie is deleted.
    log_in_as(@user, remember_me: '0')
    assert_empty cookies['remember_token']
  end
end

test_helper.rb中:

ENV['RAILS_ENV'] ||= 'test'

class ActiveSupport::TestCase
  fixtures :all

  # Returns true if a test user is logged in.
  def is_logged_in?
    !session[:user_id].nil?
  end

  # Log in as a particular user.
  def log_in_as(user)
    session[:user_id] = user.id
  end
end

class ActionDispatch::IntegrationTest

  # Log in as a particular user.
  def log_in_as(user, password: 'password', remember_me: '1')
    post login_path, params: { session: { email: user.email,
                                          password: password,
                                          remember_me: remember_me } }
  end
end

1 个答案:

答案 0 :(得分:0)

我有同样的问题。我必须解决两个问题:

  1. 确保只有一个test_helper.rb文件,并且
  2. test_helper.rb在正确的文件夹中

希望这会有所帮助!