【问题标题】:Ruby on Rails - Rspec test with Devise is failingRuby on Rails - 使用 Devise 的 Rspec 测试失败
【发布时间】:2016-01-25 17:45:30
【问题描述】:

我的 rails 应用程序中的 rspec-request-test 有问题。需要用户登录的测试失败了。我已经根据this tutorial. 实现了设计测试我还发现了许多使用类似方法的链接。例如here

这是我的 gemfile 的摘录:

gem 'devise', '~> 3.5'
gem 'devise-i18n'
gem 'devise-i18n-views'
gem 'cancancan', '~> 1.10'
gem 'rolify'
gem 'alchemy_cms', '~> 3.2.0'
gem 'rspec-core'
gem 'rspec-rails'
gem 'i18n-tasks', '~> 0.8.7'
gem 'factory_girl_rails'

这是失败的 rspec 测试:(spec/requests/campaigns_spec.rb)

require 'rails_helper'
RSpec.describe "Campaigns", type: :request do
  describe "GET /campaigns" do
    it "responds with 200" do
      sign_in_as_a_valid_user_request
      get campaigns_path
      expect(response).to have_http_status(200)
    end
  end
end

您应该只在登录后才能看到此页面。因此,在测试中,我想以用户身份(使用 FactoryGirl 创建)登录,而不是访问该站点并获得 200 个响应。在应用程序本身中,这运行良好。

spec/rails_helper.rb(摘录)

...
require 'spec_helper'
require 'rspec/rails'
require 'devise'
require 'support/devise_support'
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  config.include Devise::TestHelpers, type: :controller
  config.include Devise::TestHelpers, type: :view
  config.include ValidUserRequestHelper

  ...
end

spec/support/devise_support.rb

module ValidUserRequestHelper
  def sign_in_as_a_valid_user_request
    @user ||= FactoryGirl.create :user
    post_via_redirect user_session_path, 'user[email]' => @user.email, 'user[password]' => @user.password
  end
end

这是测试抛出的错误:

1) Campaigns GET /campaigns responds with 200
   Failure/Error: sign_in_as_a_valid_user_request
   ActionController::RoutingError:
     Alchemy::Page not found "/"
   # ./spec/support/devise_support.rb:13:in `sign_in_as_a_valid_user_request'
   # ./spec/requests/campaigns_spec.rb:6:in `block (3 levels) in <top (required)>'

根据我找到的链接,这应该可以!但它没有......谁能告诉我为什么?为什么会出现路由错误?应用程序本身运行良好。

【问题讨论】:

  • 您是否在您的路线中设置了root_path?另外,我最好将你的登录存根描述为here,而不是为每个测试提交登录请求
  • 我的 routes.rb 看起来像这样(摘录):mount Alchemy::Engine =&gt; '/' root to: redirect('/')

标签: ruby-on-rails rspec devise alchemy-cms


【解决方案1】:

发生路由错误,因为您的主机应用程序不知道引擎路由。这就是为什么您必须在当前控制器范围之外的视图中使用 rails 引擎的路由代理对象。请阅读有关 Rails 引擎及其路线特征的更多信息in the official rails guides

幸运的是,Alchemy 附带了a handy test helper,可以解决您的问题。只需将此添加到您的spec_helper

# spec/spec_helper.rb
require 'alchemy/test_support/controller_requests'
...
RSpec.configure do |config|
  config.include Alchemy::TestSupport::ControllerRequests
  ...
end

知道您可以在请求规范中使用alchemy_get 而不是get

【讨论】:

  • 谢谢!我的 spec_helper 中缺少一些“要求”语句。但是在添加这些之后,您的解决方案就可以了!
  • 很高兴听到。缺少哪些要求语句?
猜你喜欢
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多