Count; find User with id= Minitest

家住魔仙堡 提交于 2019-12-12 04:36:59

问题


I am following Michael Hartl's Ruby on Rails tutorial and I am not sure why I am getting this Error when according to the tutorial everything should pass:

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>'

My minitest:

require '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

I compared my users_controller to the official github tutorial and it looks the same

Users controller:

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

I dont really understand why id is being searched for as well. My database is empty with no users. I am currently testing that inputing invalid parameters for sign up will not add another user.

my UserControllerTest:

require '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

回答1:


Show renders a page for specific user, so you need to pass it the id param. Change the test to:

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

FYI, A small breakdown of the error message:

1) Error:

Error

UsersControllerTest#test_should_get_show:

In test test_should_get_show in class UserControllerTest

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

Database doesn't contain User object with empty id

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

File and line that directly caused the error

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

File and line where the action originated from.



来源:https://stackoverflow.com/questions/26501279/count-find-user-with-id-minitest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!