我在控制器中有这个
def destroy
@post = Post.find(params[:id])
@post.destroy
end
但是我对如何实际测试它是否有效一无所知。任何指针将不胜感激!我目前在我的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
正如所指出的,如果您使用请求规范(请参阅https://relishapp.com/rspec/rspec-rails/v/3-9/docs/request-specs/request-spec,则可以轻松调用应删除模型的API,然后执行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
您可以检查事物计数是否改变了-1,如下所示:
expect { delete '/things', :thing => { :id => 123'} }.to change(Thing, :count).by(-1)
这意味着您想少一件东西,并确保已删除某些东西。
[如果要确保删除了特定的“事物”,可以在测试之前创建一个,将“事物” ID作为参数传递,并确保它在数据库中不存在,如下所示:
thing = create(:thing)
delete '/things', :thing => { :id => thing.id'}
expect(Thing.find_by(id: thing.id)).to be_nil