2015-12-03 51 views
0

我似乎被卡住了。我正在嘗試支持一些rspec測試,並希望確保正確的before_filter方法正在爲控制器調用。但是,我收到反饋說該方法永遠不會被調用。在導軌控制器中過濾之前的測試

錯誤:

Failure/Error: expect(controller).to receive(:authorize) 
    (#<UsersController:0x007fca2fd27110>).authorize(*(any args)) 
     expected: 1 time with any arguments 
     received: 0 times with any arguments 

該規範:

require "rails_helper" 

RSpec.describe UsersController, :type => :controller do 
    let(:school){ FactoryGirl.create :school } 
    let(:user){ FactoryGirl.create :teacher} 
    before(:each){ 
    allow(controller).to receive(:current_user).and_return(user) 
    school.teachers << user 
    } 

    context "Get #show" do 
    before(:each){ get :show, school_id: school.id, id: user.id } 
    it "responds successfully with an HTTP 200 status code" do 
     expect(controller).to receive(:authorize) 
     expect(response).to have_http_status(200) 
    end 

    it "renders the show template" do 
     expect(response).to render_template("show") 
    end 
    end 
end 

控制器:

class UsersController < ApplicationController 
    before_filter :authorize 

    def show 
    @user = User.find_by_id params[:id] 
    @school = @user.school 
    @coordinators = @school.coordinators 
    @teachers = @school.teachers 
    @speducators = @school.speducators 
    @students = @school.students 
    end 
end 

手動測試顯示,之前被調用,當我把AP的當我運行測試時調用它的方法,關於測試出錯的任何想法?

回答

0

必須先將實際調用設置方法期望,讓您的測試應該是這樣的:

context "Get #show" do 
    subject { get :show, school_id: school.id, id: user.id } 

    it "calls +authorize+ befor action" do 
    expect(controller).to receive(:authorize) 
    subject 
    end 
end 

檢查文檔https://github.com/rspec/rspec-mocks#message-expectations

+0

我不熟悉的話題。我應該使用它而不是之前的塊? – AdamCooper86

+0

@ AdamCooper86。是的,但是您必須在每個測試用例中手動調用'subject'才能發出GET請求。 'hook之前'會自動運行。 'subject'語義的文檔 - https://www.relishapp.com/rspec/rspec-core/v/3-4/docs/subject/explicit-subject – andrykonchin

相關問題