[英]Ruby on rails rspec destroy count fails
我已經為簡單的應用程序編寫了一些測試。 我的authors_controller中的#destroy方法遇到問題。 當我從一些教程中完成此操作時(許多資源都顯示了類似的方法),我想它應該可以工作,但是會發生這種錯誤:
Failure/Error: expect { delete :destroy, id: author.id }.to change(Author, :count).by(-1) expected #count to have changed by -1, but was changed by 0
這是我的代碼:
author_controller_spec.rb
require 'rails_helper'
describe AuthorsController do
let(:author) { FactoryGirl.create(:author) }
describe 'DELETE #destroy' do
it 'deletes author' do
expect { delete :destroy, id: author.id }.to change(Author, :count).by(-1)
end
end
end
authors_controller.rb
class AuthorsController < ApplicationController
def show
@author = Author.find(params[:id])
end
def new
@author = Author.new
end
def create
@author = Author.new(author_params)
if @author.save
redirect_to @author
else
render 'new'
end
end
def edit
@author = Author.find(params[:id])
end
def update
@author = Author.find(params[:id])
if @author.update(author_params)
redirect_to @author
else
render 'edit'
end
end
def destroy
@author = Author.find(params[:id])
@author.books.each do |book|
book.destroy if book.authors.count == 1
end
@author.destroy
redirect_to authors_path
end
def index
@author = Author.all
end
private
def author_params
params.require(:author).permit(:name, :surname, book_ids: [])
end
end
在您第一次提到該變量之前,不會進行let
調用,因為它是惰性計算。 這意味着在您的expect
塊中,您同時在創建和銷毀記錄,導致總體變化為0。
在代碼塊之外創建author
:
describe AuthorsController do
let(:author) { FactoryGirl.create(:author) }
describe 'DELETE #destroy' do
author
it 'deletes author' do
expect { delete :destroy, id: author.id }.to change(Author, :count).by(-1)
end
end
end
或者,通過使用let!
告訴let
塊不要懶惰地求值let!
:
describe AuthorsController do
let!(:author) { FactoryGirl.create(:author) }
describe 'DELETE #destroy' do
it 'deletes author' do
expect { delete :destroy, id: author.id }.to change(Author, :count).by(-1)
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.