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

时间:2014-04-10 13:10:21

标签: ruby-on-rails rspec

我的控制器在其更新操作上有一个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

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

1 个答案:

答案 0 :(得分:1)

我建议将调用存根到Event,然后返回一个可以响应: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