新手问题 編寫測試的時候出現這個問題,stackoverflow 沒有找到適合的問題,請各位幫忙看一下如何解決 ,謝謝!

StephenZzz · 2017年09月01日 · 最后由 tinyfeng 回复于 2017年09月01日 · 473 次阅读

test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase

  fixtures :all
  #如果用戶已經登錄,返回 true
  def is_logged_in?
    !session[:user_id].nil? 
  end

  #登錄指定的用戶
  def log_in_as(user)
    session[:user_id] = user.id
  end
 end
  #登錄指定的用戶
class ActionDispatch::InterationTest
    def log_in_as(user, password: '123456', remember_me: '0')
       post login_path, params: { session: { email: user.email,
                                                                      password: password,
                                                                      remember_me: remember_me } }
    end
end

users_login_test.rb

require 'test_helper'

class UsersLoginTest < ActionDispatch::IntegrationTest

    def setup
        @user = users(:green)
    end

  test "login with valid information followed by logout" do
    get login_path
    post login_path, params: { session: { email:    @user.email, 
                                                                   password: 'password' } }

    assert is_logged_in?
        assert_redirected_to @user
        follow_redirect!
        assert_template 'users/show'
        assert_select "a[href=?]", login_path, count: 0
        assert_select "a[href=?]", logout_path
        assert_select "a[href=?]", user_path(@user)
        delete logout_path
        assert_not is_logged_in?
        assert_redirected_to root_url
        #模擬用戶在另一個窗口中點擊退出鏈接
        delete logout_path
        follow_redirect!
        assert_select "a[href=?]",login_path
        assert_select "a[href=?]",logout_path,      count: 0
        assert_select "a[href=?]",user_path(@user), count: 0
  end 

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

  test "login without remembering" do
    #登錄, 設定 cookie
    log_in_as(@user, remember_me: '1')
    delete logout_path
    #再次登錄, 確認 cookie 被刪除了
    log_in_as(@user, remember_me: '0')
    assert_empty cookies['remember_token']
  end
end
共收到 1 条回复
def log_in_as(user)
    session[:user_id] = user.id
end

log_in_as只接受一个参数,而你下面的调用传了两个参数

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

test "login without remembering" do
        #登錄, 設定 cookie
        log_in_as(@user, remember_me: '1')
        delete logout_path
        #再次登錄, 確認 cookie 被刪除了
        log_in_as(@user, remember_me: '0')
        assert_empty cookies['remember_token']
end
StephenZzz 关闭了讨论 09月01日 15:08
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册