Rails 7 和 authlogic 6.4.3 测试错误

问题描述 投票:0回答:1

我正在尝试编写一些需要身份验证的控制器测试,我目前正在使用 authlogic 6.4.3 和 Rails 7

问题是它总是抛出这个错误:

Authlogic::Session::Activation::NotActivatedError: You must activate the Authlogic::Session::Base.controller with a controller object before creating objects

如果我将其添加为 setup:activate_authlogic 它给了我这个错误:

NoMethodError: undefined method 'activate_authlogic' for #<VideosTest:0x00007f0fb982f0d0>

但我将其更改为 setup do ,现在错误是

Authlogic::Session::Activation::NotActivatedError:

这是我的 test_helper.rb

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


class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
  #
  # Note: You'll currently still have to declare fixtures explicitly in integration tests
  # -- they do not yet inherit this setting
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

# Define active_authlogic into all setup
class ActionController::TestCase

  setup do
    :activate_authlogic
  end

  def login(user)
    post sesiones_url, :params => { :email => user.email, :password => 'password' }
  end
end

这是我的测试:

require 'test_helper'

class VideosTest < ActionController::TestCase

  setup do
    @video = video(:one)
  end

  test "should get new" do
    Sesion.create(usuarios(:admin))
    get :new
    assert_response :success
  end
  
end

这种情况也会发生在需要身份验证的类似测试中。

我还尝试为登录添加一个辅助方法,但它引发了此错误:

ActionController::UrlGenerationError: No route matches {:action=>"http://test.host/sesiones", :controller=>"videos", :email=>"[email protected]", :password=>"password"}

我已经没有想法了

使用 authlogic 编写测试的正确方法是什么?或者有没有办法在测试中绕过身份验证?

ruby-on-rails ruby authlogic
1个回答
0
投票

您的测试应该继承自

ActionDispatch::IntegrationTest
而不是
ActionController::TestCase

Rails 不鼓励使用功能测试,而倾向于集成测试(使用

ActionDispatch::IntegrationTest
)。

新的 Rails 应用程序不再生成功能风格的控制器测试,它们应该仅用于向后兼容。集成样式控制器测试执行实际请求,而功能样式控制器测试仅模拟请求。此外,集成测试与功能测试一样快,并提供许多帮助器,例如

as
parsed_body
,用于有效测试控制器操作,甚至包括 API 端点。

https://api.rubyonrails.org/v7.0.0/classes/ActionController/TestCase.html

© www.soinside.com 2019 - 2024. All rights reserved.