简体   繁体   中英

how to write test case for create and update actions in rspec?

Restaurant and Location models contains HABTM association. how to write test cases for locations 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    

You can simply create the spec using the following code snippet :

 Restaurant = FactoryBot.create(:Restaurant, name: Faker::Name.name)
 post :create, params: { location: {restaurant_ids:[Restaurant.id]}, format: 'json'
 expect(response.status).to eq(200)

Try the following code to create

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)

Try the following code to update

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)

For simple controllers like this, I also like to ensure that the records are being created, so I would also test this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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