繁体   English   中英

如何编写用于在rspec中创建和更新操作的测试用例?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM