【问题标题】:Count; find User with id= Minitest数数;查找 id=Minitest 的用户
【发布时间】:2014-10-22 06:11:31
【问题描述】:

我正在关注 Michael Hartl 的 Ruby on Rails 教程,但我不确定为什么在按照教程一切都应该通过时出现此错误:

1) Error:
UsersControllerTest#test_should_get_show:
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=
    app/controllers/users_controller.rb:7:in `show'
    test/controllers/users_controller_test.rb:10:in `block in <class:UsersControllerTest>'

我的小测试:

需要'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest
  # add invalid information and test that the User.count never changes
  # also test that the sign up path is visited after invalid sign up
  test "invalid signup information" do
    # visit the signup path using get
    get signup_path
    assert_no_difference "User.count" do
      post users_path, user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar"}
    end
    assert_template "users/new"
  end  
end

我将我的 users_controller 与官方 github 教程进行了比较,看起来一样

用户控制器:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    # strong parameters
    @user = User.new(user_params)
    if @user.save
      # handle save
    else
      render 'new'
    end
  end

  private
    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end
end

我真的不明白为什么还要搜索id。我的数据库是空的,没有用户。我目前正在测试输入无效参数进行注册不会添加其他用户。

我的用户控制器测试:

需要'test_helper'

class UsersControllerTest < ActionController::TestCase
  test "should get new" do
    get :new
    assert_response :success
  end

  test "should get show" do
    get :show
    assert_response :success
  end
end

【问题讨论】:

  • 您发布的测试很好。失败的一个是UsersControllerTest。如果您附上它,我们可以尝试帮助您。很可能您请求的用户路径 ID 不正确或缺失。
  • @makhan 我再看看谢谢!
  • @makhan 我想我把代码放在了项目的错误部分。感谢您指出这一点!
  • get :show之前添加user = User.create并将get :show更改为get :show, id: user.id

标签: ruby-on-rails ruby minitest


【解决方案1】:

Show 为特定用户呈现页面,因此您需要将 id 参数传递给它。将测试更改为:

  test "should get show" do
    user = User.create
    get :show, id: user.id
    assert_response :success
  end

仅供参考,错误消息的小分类:

1) Error:

错误

UsersControllerTest#test_should_get_show:

在测试中test_should_get_show 在课堂上UserControllerTest

ActiveRecord::RecordNotFound: Couldn't find User with 'id'=

数据库不包含带有空idUser 对象

    app/controllers/users_controller.rb:7:in `show'

直接导致错误的文件和行

    test/controllers/users_controller_test.rb:10:in `block in <class:UsersControllerTest>'

动作源自的文件和行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 2021-10-23
    • 2021-12-26
    • 2014-02-21
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    相关资源
    最近更新 更多