繁体   English   中英

Rspec:如何测试控制器的around_action过滤器?

[英]Rspec: How to test a controller's around_action filter?

我的控制器在其update动作上有一个around_action过滤器,以在更新特定属性时触发特定行为。 如下所示:

class EventsController < ApplicationController
  around_action :contact_added_users

  def contact_added_users
    @event = Event.find(params[:id])
    existing_users = @event.users
    yield
    added_users = @event.users.reject{|u| existing_users.include? u }
    added_users.each { |u| u.contact }
  end
end

我已经验证它可以手动运行,但是如何在Rspec中测试我的around_action过滤器? 我已经尝试过类似的东西:

describe EventsController do
  describe "PUT update" do
    let(:event) { FactoryGirl.create(:event) }
    let(:old_u) { FactoryGirl.create(:user) }
    let(:new_u) { FactoryGirl.create(:user) }
    before(:each) { event.users = [ old_u ]
                    event.save }

    context "when adding a user" do
      it "contacts newly added user" do
        expect(new_u).to receive(:contact)
        expect(old_u).not_to receive(:contact)

        event_params = { users: [ old_u, new_u ] }
        put :update, id: event.id, event: event_params
      end
    end

...但是失败了。 还尝试添加

    around(:each) do |example|
      EventsController.contact_added_users(&example)
    end

但仍然没有骰子。 如何正确测试?

我建议暂挂对Event的调用,并返回一个可以响应:users的双精度值,以提供通过规范所需的结果。 窍门是:users必须两次调用:users ,结果不同。 RSpec允许您传递将为后续调用返回的值的列表:

let(:existing_users) { [user_1, user_2] }
let(:added_users) { [user_3] }
let(:event) { double('event') {

before(:each) do
  Event.stub(:find).with(params[:id]) { event }
  event.should_receive(:users).exactly(2).times.and_return(existing_users, added_users)
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM