我创建了一个destroy方法,现在我想知道如何测试和渲染对象是否被删除。
def destroy if @syllabus.destroy render :no_content else endend
def destroy
if @syllabus.destroy
render :no_content
else
end
ufj5ltwl1#
我认为您正在寻找类似rspec rails的东西,在遵循gem存储库上的安装说明后,您可以使用以下内容生成测试文件: bundle exec rails generate rspec:controller my_controller 这将生成如下所示的文件:
bundle exec rails generate rspec:controller my_controller
# spec/controllers/my_controller_spec.rbrequire '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
# your code goes here...
然后,您可以添加如下测试示例:
# spec/controllers/my_controller_spec.rbrequire '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) endend
#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)
上面的代码不是测试代码,它只是作为一个指南
对于你来说,破坏动作法是可以的,但是如果你把它放在下面,你可以对它进行一些改进:
def destroy @syllabus.destroy end
@syllabus.destroy
这是因为if/else条件对该方法没有太大作用,rails在默认情况下应该以 204 no content
204 no content
1条答案
按热度按时间ufj5ltwl1#
我认为您正在寻找类似rspec rails的东西,在遵循gem存储库上的安装说明后,您可以使用以下内容生成测试文件:
bundle exec rails generate rspec:controller my_controller
这将生成如下所示的文件:然后,您可以添加如下测试示例:
上面的代码不是测试代码,它只是作为一个指南
对于你来说,破坏动作法是可以的,但是如果你把它放在下面,你可以对它进行一些改进:
这是因为if/else条件对该方法没有太大作用,rails在默认情况下应该以
204 no content