提问人:jamal 提问时间:7/15/2021 更新时间:7/16/2021 访问量:316
如何确认对象是否在 rails-for-API 中删除?
how to confirm if the object was deleted in rails-for-API?
问:
我创建了一个 destroy 方法,现在我想知道如何测试和渲染对象是否设法被删除。
def destroy
if @syllabus.destroy
render :no_content
else
end
end
答:
1赞
Mihail Pozarski
7/16/2021
#1
我想你正在寻找像 rspec-rails 这样的东西, 按照 Gem 存储库上的安装说明操作后,您可以使用以下命令生成测试文件:
bundle exec rails generate rspec:controller my_controller
这将生成如下所示的文件:
# spec/controllers/my_controller_spec.rb
require 'rails_helper'
RSpec.describe MyControllerController, type: :controller do
# your code goes here...
end
然后,您可以添加一个测试示例,如下所示:
# spec/controllers/my_controller_spec.rb
require 'rails_helper'
RSpec.describe MyControllerController, type: :controller do
#replace attr1 and attr2 with your own attributes
let(:syllabus) { Syllabus.create(attr1: 'foo', attr2: 'bar') }
it 'removes syllabus from table' do
expect { delete :destroy, id: syllabus.id }.to change { Syllabus.count }.by(-1)
end
end
** 上面的代码不是测试,它只是作为指南制作的 **
对于你来说,销毁操作方法没关系,但是,如果你像这样离开它,你可以改进它:
def destroy
@syllabus.destroy
end
这是因为你的 if/else 条件对方法没有做太多事情,默认情况下 Rails 应该用204 no content
评论
destroy