在rails控制器中测试之前的过滤器

时间:2015-12-03 04:00:28

标签: ruby-on-rails ruby rspec

我好像被卡住了。我试图支持一些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

手动测试显示在调用之前,当我在authorize方法中放入p时,在运行测试时会调用它,对测试出错的地方有任何想法吗?

1 个答案:

答案 0 :(得分: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