【问题标题】:"should get show" controller test failing for Nested resource嵌套资源的“应该显示”控制器测试失败
【发布时间】:2015-04-05 20:07:19
【问题描述】:

我有一个User 模型和一个Shoppingcart 模型,其中

# user.rb
class User < ActiveRecord::Base
    has_one :shoppingcart
end

和

# shopppingcart.rb
class Shoppingcart < ActiveRecord::Base
    belongs_to :user
end

我在 routes.rb 中有这个:

resources :users do
    resource :shoppingcart
end

在 Shoppingcarts_controller.rb 我有

class ShoppingcartsController < ApplicationController
    def show
        @user = User.find(current_user)
        @shoppingcart = @user.build_shoppingcart
    end
end

在 shoppingcarts_controller_test.rb 中:

require 'test_helper'
class ShoppingcartsControllerTest < ActionController::TestCase
    def setup
        @user = users(:michael)
    end
    test "should get show" do
        puts(@user.name) # => Michael Example
        puts(@user.id) # => 762146111
        get :show # error line
        assert_response :success
    end
end

但是当我运行测试时,我得到ActiveRecord::RecordNotFound: Couldn't find User with 'id'=。当我注释掉错误行时,错误消失并且一切正常。至于非测试代码,一切正常。我可以毫无问题地联系到users/1/shoppingcart,所以问题一定来自测试本身。如何对嵌套资源的操作进行测试?

SessionsHelper.rb:

module SessionsHelper

    # Returns the current logged-in user (if any).
    def current_user
        if (user_id = session[:user_id])
            @current_user ||= User.find_by(id: user_id)
        elsif (user_id = cookies.signed[:user_id])
            user = User.find_by(id: user_id)
            if user && user.authenticated?(:remember, cookies[:remember_token])
                log_in user
                @current_user = user
            end
        end
    end
end 

【问题讨论】:

  • current_user 是如何定义的?如果您能找出它返回 nil 的原因,那么您将得到答案
  • current_user 实现已在此处添加

标签: ruby-on-rails ruby-on-rails-4 nested-resources ruby-test


【解决方案1】:

find 方法需要来自Users 表的特定用户的主键,而不是用户本身。主键是id,因此您需要在控制器中更改此行。

@user = User.find(params[:user_id])

【讨论】:

  • 现在错误看起来像NoMethodError: undefined method id for nil:NilClass
  • 我认为,那是因为您的测试中没有current_user,因为您没有登录@user。我已经更新了答案,它应该可以工作。
  • 你的代码错了,但你的想法是对的!我没有登录。我在设置操作的末尾添加了 logged_in_as(@user) 测试类并将控制器中的那一行更改为 @user = User.find(current_user.id)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多