如何在rails中编写destroy方法的测试用例?

时间:2015-06-25 06:07:06

标签: ruby-on-rails ruby-on-rails-4 rspec

#Destroy Action method
def destroy
  Key.destroy(params[:id])
end
-------------------------------
#testcase for this
 expect(delete :destroy ,{"id"=>"3"}).to change(Key, :count).by(-1)

显示Action视图::模板缺失错误无法在rails中为void操作(不返回任何内容/无渲染)方法编写测试用例。

现在我改变了我的方法来渲染json值。

def destroy
  Key.destroy(params[:id])
  respond_to do |format|
    format.html {}
    format.json { head :no_content }
  end
end

现在我对运行测试用例的断言是:

it "should destroy" do
   response=delete :destroy ,{"id"=>"3"}
   expect(response).to have_http_status(204)
end

1 个答案:

答案 0 :(得分:0)

您可以使用Factory创建样本项(例如Factory Girl),然后检查它是否存在。这是一个示例销毁测试(查询是针对Mongoid数据库的,但是你可以得到它。 在我的情况下,我的destroy方法有一个json响应,也可以检查(但我不在这里做)。

   let(:key_to_delete) {FactoryGirl.create(:key)}

   it 'should destroy' do
      delete :destroy, id: key_to_delete.id
      expect(Key.where(id: key_to_delete.id).count).to eq(0)
    end
相关问题