2015-07-13 142 views
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 

回答

1

直到第一次提到变量时才会调用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!

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 
+0

啊,感谢您的回答和解释。我找到了这样的解决方案,它的工作,但只是不知道为什么这样。 – Hedselu

+0

没问题。如果有效,请将其标记为接受的答案,以便下一个人知道。 –

+0

不得不等待 - 可能我办公室里很多人使用堆栈:) – Hedselu

相关问题