0
我已經爲簡單的應用程序編寫了一些測試。我在我的authors_controller中遇到了#destroy方法的問題。正如我已經這樣做了一些教程(許多來源顯示類似的方法),我想它應該工作,但是發生這樣的錯誤:Ruby on rails rspec銷燬計數失敗
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
啊,感謝您的回答和解釋。我找到了這樣的解決方案,它的工作,但只是不知道爲什麼這樣。 – Hedselu
沒問題。如果有效,請將其標記爲接受的答案,以便下一個人知道。 –
不得不等待 - 可能我辦公室裏很多人使用堆棧:) – Hedselu