简体   繁体   English

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

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

My controller has an around_action filter on its update action, to trigger specific behavior if a particular attribute is updated. 我的控制器在其update动作上有一个around_action过滤器,以在更新特定属性时触发特定行为。 Something like below: 如下所示:

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

I've verified that it works manually, but how can I test my around_action filter in Rspec? 我已经验证它可以手动运行,但是如何在Rspec中测试我的around_action过滤器? I've tried something like: 我已经尝试过类似的东西:

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

...but it fails. ...但是失败了。 Also tried adding 还尝试添加

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

but still no dice. 但仍然没有骰子。 How can I test this correctly? 如何正确测试?

I'd suggest stubbing the call to Event and returning a double that can respond to :users with the results you need for the spec to pass. 我建议暂挂对Event的调用,并返回一个可以响应:users的双精度值,以提供通过规范所需的结果。 The trick is that :users must be called twice with different results. 窍门是:users必须两次调用:users ,结果不同。 RSpec allows you to pass a list of values that will be returned for successive calls: 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