2015-12-03 69 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

相关问题