【发布时间】:2021-05-20 22:53:55
【问题描述】:
我正在为我的应用添加一些 Capybara/RSpec 测试,但在控制器的 create 方法中遇到了一些问题。
这是我的测试:
require 'rails_helper'
RSpec.describe Api::V1::CampgroundsController, type: :controller do
let(:campground_data) { FactoryBot.create :campground_1 }
let(:user) { FactoryBot.create :user_2 }
describe 'POST#create' do
it "admin should be able to create new campgrounds" do
sign_in user
before_count = Campground.count
post :create, params: campground_data, format: JSON
after_count = Campground.count
expect(after_count).to eq(before_count + 1)
end
end
end
露营地控制器 - 创建方法:
def create
binding.pry
campground = Campground.new(campground_params)
if campground.save
render json: campground
else
render json: { errors: campground.errors.full_messages }
end
end
强参数:
def campground_params
params.require(:campground).permit([:name, :caption, :description, :location, :zip_code, :campground_link, :dogs_allowed, :electric_hookups, :water_hookups, :potable_water, :dump_station, :bathrooms, :showers])
end
当我运行测试时,它在这一行失败:post :create, params: campground_data, format: JSON。它返回的错误是undefined method symbolize_keys' for #Campground:0x00007f9887ca4910`
我被这个问题困扰了很长一段时间,经过数小时的谷歌搜索、搜索文档和查看旧帖子后,我仍然不确定问题出在哪里。 create 方法在生产中有效,但我不知道我需要做什么才能让它在 RSpec 中工作。我假设我在传递数据的方式上做错了,但我不确定该怎么做。我确实尝试使用 FactoryBot 创建露营地,然后这样做:
campground = {
name: campground.name,
caption: campground.caption,
description: campground.description,
location: campground.location,
zip_code: campground.zip_code,
campground_link: campground.campground_link,
dogs_allowed: campground.dogs_allowed,
electric_hookups: campground.electric_hookups,
water_hookups: campground.water_hookups,
potable_water: campground.potable_water,
dump_station: campground.dump_station,
bathrooms: campground.bathrooms,
showers: campground.showers }
当我这样做时,我不再收到symbolize_keys 错误,我在控制器上使用create 方法,但是当它到达campground = Campground.new(campground_params) 这一行时,它会出现错误:ActionController::ParameterMissing: param is missing or the value is empty: campground我主要以这种方式进行测试,但我认为这不是创建要传递给控制器的数据的正确方法。我觉得我的第一种方法应该行得通,而且是一种更清洁的方法……我只是不知道我做错了什么。
【问题讨论】:
标签: ruby-on-rails ruby rspec rspec-rails