[英]how to write test case for create and update actions in 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: { location: {restaurant_ids:[Restaurant.id]}, format: 'json'
expect(response.status).to eq(200)
嘗試以下代碼創建
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)
對於像這樣的簡單控制器,我也想確保創建了記錄,因此我還要測試一下:
restaurant = FactoryBot.create(:restaurant, name: Faker::Name.name)
expect {
post(
:create,
params: {
restaurant_id: restaurant.id,
location: { restaurant_ids:[restaurant.id] },
format: 'js'
}
)
}.to change{ Location.count }.by(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.