Ruby Rails - Rspec Devise 测试失败

Ruby on Rails - Rspec test with Devise is failing

我的 rails 应用程序中的 rspec-request-test 有问题。需要用户登录的测试失败。我已经根据 this tutorial. Also I found many links, that are using a similar approach. e.g. 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)>'

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

发生路由错误,因为您的主机应用不知道引擎路由。这就是为什么您必须在当前控制器范围之外的视图中使用 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