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

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

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

def destroy
  if @syllabus.destroy
    render :no_content
  else 
  end
end
ufj5ltwl

ufj5ltwl1#

我认为您正在寻找类似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

相关问题