ruby-on-rails - 如何为 rspec 中的创建和更新操作编写测试用例?
问题描述
餐厅和位置模型包含 HABTM 关联。如何为位置控制器编写测试用例
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)
推荐阅读
- python - 建立一个基本的分类网站并得到一个 Python SQLite 错误
- python - python:如何在包含列表列表的字典中查找索引
- php - PHP Encoding JSON Issue
- python - 如何显示已成功交付给客户/用户的每个产品的帐单地址
- python - 如何在 mininet 中使用 miniedit?任何人都可以建议命令
- angular - 如何在生产代码中隐藏敏感数据?
- http - 日志分析查询汇总 dau 明智的所有 http 错误计数
- r - 如何正确描述 5D 张量?(keras, r)
- python - python中svg的非线性变换
- dictionary - Leafletjs 地图交互式 Choropleth 地图