如何确认对象是否已在RailsforAPI中删除?

wqlqzqxt  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(334)

我创建了一个destroy方法,现在我想知道如何测试和渲染对象是否被删除。

  1. def destroy
  2. if @syllabus.destroy
  3. render :no_content
  4. else
  5. end
  6. end
ufj5ltwl

ufj5ltwl1#

我认为您正在寻找类似rspec rails的东西,在遵循gem存储库上的安装说明后,您可以使用以下内容生成测试文件: bundle exec rails generate rspec:controller my_controller 这将生成如下所示的文件:

  1. # spec/controllers/my_controller_spec.rb
  2. require 'rails_helper'
  3. RSpec.describe MyControllerController, type: :controller do
  4. # your code goes here...
  5. end

然后,您可以添加如下测试示例:

  1. # spec/controllers/my_controller_spec.rb
  2. require 'rails_helper'
  3. RSpec.describe MyControllerController, type: :controller do
  4. #replace attr1 and attr2 with your own attributes
  5. let(:syllabus) { Syllabus.create(attr1: 'foo', attr2: 'bar') }
  6. it 'removes syllabus from table' do
  7. expect { delete :destroy, id: syllabus.id }.to change { Syllabus.count }.by(-1)
  8. end
  9. end

上面的代码不是测试代码,它只是作为一个指南

对于你来说,破坏动作法是可以的,但是如果你把它放在下面,你可以对它进行一些改进:

  1. def destroy
  2. @syllabus.destroy
  3. end

这是因为if/else条件对该方法没有太大作用,rails在默认情况下应该以 204 no content

展开查看全部

相关问题