Ruby on rails 如何为rspec中的创建和更新操作编写测试用例?
餐厅和位置模型包含HABTM协会。 如何为控制器编写测试用例Ruby on rails 如何为rspec中的创建和更新操作编写测试用例?,ruby-on-rails,Ruby On Rails,餐厅和位置模型包含HABTM协会。 如何为控制器编写测试用例 def create @restaurant = Restaurant.find(params[:restaurant_id]) @location = @restaurant.locations.create(location_params) if @location.save flash[:notice] = 'Location added!' redirect
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)
它显示失败/错误:@restaurant=restaurant.find(params[:restaurant_id])nomethoderor:for的未定义方法“find”#