gpt4 book ai didi

ruby-on-rails - 如何为 rspec 中的创建和更新操作编写测试用例?

转载 作者:行者123 更新时间:2023-12-03 16:02:32 25 4
gpt4 key购买 nike

餐厅和位置模型包含 HABTM 关联。
如何为位置 Controller 编写测试用例

def create
@restaurant = Restaurant.find(params[:restaurant_id])
@location = @restaurant.locations.create(location_params)
if @location.save
flash[:notice] = 'Location added!'
redirect_to admin_locations_path
else
flash[:error] = 'Failed to edit location!'
render :new
end
end

def update
@location = Location.find(params[:id])
if @location.update_attributes(location_params)
flash[:notice] = 'Location updated!'
redirect_to admin_locations_path
else
flash[:error] = 'Failed to edit Location!'
render :edit
end
end

最佳答案

尝试以下代码创建

restaurant = FactoryBot.create(:restaurant, name: Faker::Name.name)
post :create, params: { restaurant_id: restaurant.id, location: {restaurant_ids:[restaurant.id]}, format: 'js' }
expect(response).to have_http_status(:success)

试试下面的代码更新
restaurant = FactoryBot.create(:restaurant, name: Faker::Name.name)
location = FactoryBot.create(:location, restaurant_id: restaurant.id)
patch :update, params: { id: location.id, location: {restaurant_ids:[restaurant.id]}, format: 'js' }
expect(response).to have_http_status(:success)

关于ruby-on-rails - 如何为 rspec 中的创建和更新操作编写测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57386682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com