首页 > 解决方案 > 如何为 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    

标签: ruby-on-rails

解决方案


尝试以下代码创建

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)

推荐阅读