Count; find User with id= Minitest

2019-09-17 10:04发布

问题:

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.