0

我在控制器中有这个

   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 
4

2 回答 2

1

您可以检查事物的计数是否更改了 -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
于 2019-10-13T03:48:21.227 回答
0

正如所指出的,如果您使用请求规范(请参阅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
于 2019-10-12T23:20:45.200 回答