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