为什么我的测试会尝试呈现不同且无效的路线?

Why does my test try to render a different & invalid route?

我有一个测试试图查看不存在的订阅。我 运行 与我的灯具中的一群用户进行了此测试。在用户处于管理员角色的情况下,当应用程序到达尝试呈现响应的点时,它已将操作从 :show 更改为 :edit 并删除了 id 参数。然而,当我尝试使用 byebug 来跟踪执行时,我似乎永远无法确定它何时发生。

我的测试是:

test "#{u.role} can not view subscriptions that don't exist" do
  self.send('sign_in_' + u.role)
  get :show, id:1234567890
  assert_redirected_to root_path
  assert_includes flash[:alert], "That subscription doesn't exist"
end

其中 u 是从我的灯具加载的用户。

我得到的错误是:

SubscriptionsControllerTest#test_admin_can_not_view_subscriptions_that_don't_exist:
ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"subscriptions", :id=>nil} missing required keys: [:id]
    app/views/subscriptions/show.html.erb:13:in `_app_views_subscriptions_show_html_erb__1518678276755260966_70268849069860'
    test/controllers/subscriptions_controller_test.rb:58:in `block (2 levels) in <class:SubscriptionsControllerTest>'

我的控制器看起来像这样:

class SubscriptionsController < ApplicationController
  load_and_authorize_resource except: [:create,:new]
  before_action :set_subscription
  def show
  end
  def edit
  end
...
  private
    def subscription_params
      params.require(:subscription).permit(:email,:confirmed)
    end
    def set_subscription
      #byebug if user_signed_in? && current_user.role == 'admin' && self.action_name == 'show'
        begin
          if (params.has_key? :id) && (controller_name == 'subscriptions')
            @subscription = Subscription.find(params[:id])
          elsif user_signed_in?
            @subscription = current_user.subscription || Subscription.new(email: current_user.email)
          else
            @subscription = Subscription.new
          end
        rescue ActiveRecord::RecordNotFound
          @subscription = Subscription.new
          flash.alert = "That subscription doesn't exist"
        end
    end
end

load_and_authorize_resource来自康康康。

我与此测试相关的路线是:

  resources :subscriptions do
    member do
      get 'confirm'
    end
  end

我真的不知道从这里去哪里,所以任何建议将不胜感激。

查看您的错误信息。它说缺少 id 参数。您可能给它一个 nil 值。因此,路由器无法正确路由请求。

此外,错误是针对 edit 操作的请求,但您显示的代码正在调用 show 操作。您能否清理显示的代码示例和错误消息并使它们保持一致?

查看此异常的堆栈跟踪:

SubscriptionsControllerTest#test_admin_can_not_view_subscriptions_that_don't_exist:
ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"subscriptions", :id=>nil} missing required keys: [:id]
    app/views/subscriptions/show.html.erb:13:in `_app_views_subscriptions_show_html_erb__1518678276755260966_70268849069860'
    test/controllers/subscriptions_controller_test.rb:58:in `block (2 levels) in <class:SubscriptionsControllerTest>'

app/views/subscriptions/show.html.erb,第 13 行。您是否使用 nil ID 调用 link_to(或类似的辅助方法)?