1

我不太确定如何解释这一点。

我有一个运行 RSpec 2.8.1 的现有 Rails 3.1.3 应用程序,包含 284 个测试的测试套件。他们会很高兴地一遍又一遍地执行。

我今天添加了一个新测试,供用户更新他们的设置 -

require 'spec_helper'

describe UserSettingsController do

  describe 'PUT "update"' do

    let!(:user) { Fabricate :user }

    it 'updates the User with the correct attributes' do
      proxy = double('proxy')   #.as_null_object
      controller.should_receive(:current_user).any_number_of_times { proxy }

      attributes = Fabricate(:user_settings).stringify_keys
      proxy.should_receive(:update_attributes).with(attributes, :as => :updater) { true }

      login_user(user)
      put :update, :user => attributes
    end

  end

end

最初,此测试失败,因为我的 application_controller.rb 中有一个 before_filter 也引用了 current_user(这会导致模拟上出现意外消息),所以我想将模拟设为空对象(请参阅上面的注释区域)。

当我这样做时......整个测试套件就像在一个无限循环中一样,在完成测试之后(但在继续下一个测试之前)。

有没有人见过这样的事情?我是否错误地使用了 .as_null_object ?

编辑:澄清一些事情,login_user是 Sorcery 提供的用于在测试中进行身份验证的助手,而:user_settings制造者只是在制造一个带有时区的哈希。

4

1 回答 1

1

除非你:user_settings的工厂是自我参照的,否则我会看看做两件事。第一的:

describe UserSettingsController do

  describe 'PUT "update"' do
    let(:proxy) { double('proxy').as_null_object }
    let(:user) { Fabricate :user }

    before(:each) do
      login_user(user)
    end

    it 'updates the User with the correct attributes' do
      controller.should_receive(:current_user).any_number_of_times { proxy }

      attributes = Fabricate(:user_settings).stringify_keys
      proxy.should_receive(:update_attributes).with(attributes, :as => :updater) { true }

      put :update, :user => attributes
    end

  end

end

如果这像以前一样失败,您就知道问题出在巫术内部的某个地方。(您永远不会在控制台中看到示例摘要字符串输出。)请注意,我保留了#as_null_object调用:巫术将提示被模拟的用户获取信息,主要是填充哈希值。如果您有兴趣,请从这里开始阅读。如果无助于查明问题,请考虑login_user完全删除。像这样:

describe UserSettingsController do

  describe 'PUT "update"' do
    let(:proxy) { double('proxy') }
    let(:user) { Fabricate :user }

    it 'updates the User with the correct attributes' do
      controller.should_receive(:current_user).any_number_of_times { proxy }

      attributes = Fabricate(:user_settings).stringify_keys
      proxy.should_receive(:update_attributes).with(attributes, :as => :updater) { true }

      put :update, :user => attributes
    end

  end

end

你正在current_user被控制器定义,我认为这意味着你会通过你的 before_filter 身份验证钩子,定义current_userproxy. 如果在所有调用中都发生了一些愚蠢的事情,那么您至少已经减少了其中的一些。

我还在猜测——我没有构建示例应用程序。祝你好运。

于 2012-01-18T05:44:55.213 回答