Reputation: 55
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:
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
Upvotes: 0
Views: 3690
Reputation: 111
You can check if the count of thing has change by -1, like this:
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:
thing = create(:thing)
delete '/things', :thing => { :id => thing.id'}
expect(Thing.find_by(id: thing.id)).to be_nil
Upvotes: 1
Reputation: 683
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.
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
Upvotes: 1