我运行测试rspec spec / controllers / lost_pets_controller_spec.rb并在线上出现错误获取:show,id:lost_pet :
require 'rails_helper'
RSpec.describe LostPetsController, type: :controller do
let(:lost_pet) { create(:lost_pet) }
describe "Get #Index" do
let(:lost_pets) { create_list(:lost_pet, 2) }
before{ get :index }
it "populates an array of all lost_pets" do
expect(assigns(:lost_pets)).to match_array(lost_pets)
end
it "renders index view" do
expect(response).to render_template(:index)
end
end
describe 'Get #show' do
before do
get :show, id: lost_pet
end
it 'assings the requested lost pet to @lost_pet' do
expect(assigns(:lost_pet)).to eq lost_pet
end
it 'renders show view' do
expect(response).to render_template(:show)
end
end
end
lostpetscontroller.rb
class LostPetsController < ApplicationController
before_action :load_lost_pet, only: [:show]
respond_to :html
def index
@lost_pets = LostPet.all
end
def show
@lost_pet
end
private
def load_lost_pet
@lost_pet = LostPet.find(params(:id))
end
def lost_pet_params
params.require(:lost_pet).permit([:id, :name, :type_pet, :breed, :gender, :size,
:colour, :age, :age_unit, :description, :collar_description, :desexed,
:microchipped, :microchip_number, :date_missing, :rewald, :image, :adress_lost,
:name_host, :telephone, :email ])
end
end
登录终端:
LostPetsController Get #show assings the requested lost pet to @lost_pet
Failure/Error: get :show, id: lost_pet
ArgumentError:
wrong number of arguments (1 for 0)
# /usr/local/rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_controller/metal/strong_parameters.rb:656:in `params'
# ./app/controllers/lost_pets_controller.rb:18:in `load_lost_pet'
为什么错误的数字参数为动作显示错误?怎么解决这个问题? 感谢提前帮助。
答案 0 :(得分:2)
更改行:
@lost_pet = LostPet.find(params(:id))
要:
@lost_pet = LostPet.find(params[:id])
(注意方括号)
答案 1 :(得分:1)
错误消息:
ArgumentError:
wrong number of arguments (1 for 0)
表示您正在调用方法并提供一个参数,但该方法不接受任何参数,因此“1表示0”。哪种方法?这是回溯中的第一个:
/usr/local/rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_controller/metal/strong_parameters.rb:656:in `params'
params
返回参数哈希。您可以在控制器中快速查看错误原因:
@lost_pet = LostPet.find(params(:id))
使用方括号而不是parens来修复它:
@lost_pet = LostPet.find(params[:id])