[英]Testing destroy with RSpec
I have this in controllers我在控制器中有这个
def destroy
@post = Post.find(params[:id])
@post.destroy
end
But I'm lost as to how to actually test if it works.但是我不知道如何实际测试它是否有效。 Any pointers would be highly appreciated: I currently have this in my RSpec file:任何指针将不胜感激:我目前在我的 RSpec 文件中有这个:
require 'rails_helper'
RSpec.describe Post, type: :model do
it "must have a title" do
post= Post.create
expect(post.errors[:title]).to_not be_empty
end
it "must have a description" do
post= Post.create
expect(post.errors[:description]).to_not be_empty
end
it "must have a location" do
post= Post.create
expect(post.errors[:location]).to_not be_empty
end
it "must have an image" do
post= Post.create
expect(post.errors[:image]).to_not be_empty
end
it "can be destroyed" do
post= Post.destroy
end
end
You can check if the count of thing has change by -1, like this:您可以检查事物的计数是否更改了 -1,如下所示:
expect { delete '/things', :thing => { :id => 123'} }.to change(Thing, :count).by(-1)
This means that you want to have one less 'thing' and and is ensuring that something has been deleted.这意味着您想要少一件“东西”,并确保某些东西已被删除。
If you want to ensure that specific "thing" was deleted, you can create one before the test, pass the "thing" id as param, and ensure that this doesn't exists on database, like this:如果要确保删除了特定的“事物”,可以在测试之前创建一个,将“事物” id 作为参数传递,并确保数据库中不存在该“事物”,如下所示:
thing = create(:thing)
delete '/things', :thing => { :id => thing.id'}
expect(Thing.find_by(id: thing.id)).to be_nil
As pointed out, if you use request specs ( see https://relishapp.com/rspec/rspec-rails/v/3-9/docs/request-specs/request-spec ) you can easily call the API that should delete the model, and then do an ActiveRecord query to expect no results.正如所指出的,如果您使用请求规范(请参阅https://relishapp.com/rspec/rspec-rails/v/3-9/docs/request-specs/request-spec ),您可以轻松调用应该删除的 API model,然后执行 ActiveRecord 查询以期望没有结果。
require "rails_helper"
RSpec.describe "delete thing api" do
it "deletes thing" do
// Create a thing with a factory of your choice here
delete "/things", :thing => {:id => 1}
expect(Thing.all.count).to be 0
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.