2016-05-31 18 views
1

我使用Rails 4.2和Rspec 3.4。我有3个控制器测试,测试闪光消息以查看是否显示正确的消息。其中两人正在工作,一人不在。我看不出工作人员和不工作人员之间的区别。Rspec 3.4/Rails 4.2:在一个规范中测试Flash消息失败,但不是其他两个测试

我的控制器看起来是这样的:

before_filter :logged_in_as_team_member, except: [:index, :show, :choose_revisions_to_diff, :diff_results] 

def destroy 
    doc = Document.find(params[:id]) 
    if doc.owners.include?(@user) && !doc.document_revisions.any? 
    doc.destroy 
    redirect_to documents_url, notice: "Document successfully deleted." 
    else 
    redirect_to documents_url, flash: { error: "Could not delete document because you are not an owner or the document has revisions assigned to it." } 
    end 
end 


private 
def logged_in_as_team_member 
    redirect_to root_url, flash: { error: "You must be a Devcomm team member to perform this action." } unless @user.is_devcomm 
end 

我Rspec的是这样的:

describe "DELETE #destroy" do 

    ### This test fails 
    it "as devcomm when user is owner returns success" do 
    devcomm_user 
    delete :destroy, id: documents(:nonsecretdocument1) 
    expect(response).to redirect_to(action: :index) 
    expect(flash[:notice]).to match "Document successfully deleted." 
    end 

    ### This test passes 
    it "as devcomm when user is not owner redirects to documents#index" do 
    devcomm_user 
    delete :destroy, id: documents(:nonsecretdocument2) 
    expect(response).to redirect_to(action: :index) 
    expect(flash[:error]).to match "Could not delete document because you are not an owner." 
    end 

    ### This test passes 
    it "as nondevcomm redirects to root_url" do 
    nondevcomm_user 
    delete :destroy, id: documents(:nonsecretdocument2) 
    expect(response).to redirect_to(root_url) 
    expect(flash[:error]).to match "You must be a Devcomm team member to perform this action." 
    end 
end 

错误:

Failures: 

    1) DocumentsController DELETE #destroy as devcomm when user is owner returns success 
    Failure/Error: expect(flash[:notice]).to match "Document successfully deleted." 
     expected nil to match "Document successfully deleted." 
    # ./spec/controllers/documents_controller_spec.rb:114:in `block (3 levels) in <top (required)>' 

任何人都可以看到,为什么第一次测试失败,另外两个传球?

编辑添加:当我在用户界面中删除文档时,闪光灯按预期显示。

回答

0

想通了。我正在使用夹具并添加了另一个模型。这个新模型依赖于documents(:nonsecretdocument1),由于我对允许删除的文档存在限制,导致文档未被删除。

+1

我发现测试您在控制器操作中修改的记录很有帮助。在这种情况下,类似'expect{@record.reload}.to raise_error(ActiveRecord :: RecordNotFound)' –