【问题标题】:Strange errors in tests after updating to rspec3更新到 rspec3 后测试中出现奇怪的错误
【发布时间】:2015-04-04 20:14:20
【问题描述】:

将项目更新到 Rspec 3 后,我的测试中出现以下我无法修复的奇怪错误:

 undefined method `empty?' for 2:Fixnum
 # /opt/local/lib/ruby2.1/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:251:in `block in missing_keys'
 # /opt/local/lib/ruby2.1/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:251:in `select'
 # /opt/local/lib/ruby2.1/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:251:in `missing_keys'
 # /opt/local/lib/ruby2.1/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:231:in `optimized_helper'
 # /opt/local/lib/ruby2.1/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:220:in `call'
 # /opt/local/lib/ruby2.1/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:345:in `block (2 levels) in define_url_helper'
 # ./app/controllers/users_controller.rb:10:in `block in <class:UsersController>'

users_controller 第 10 行包含重定向:

  redirect_to(user_path(current_user))

在每种情况下,current_user 都是使用mock_model(User, login: User.make_token) 创建的模拟用户对象,并在错误消息中引用了 ID 值(在“:Fixnum”之前)。

每个包含对象的重定向都会发生这种情况。例子:

redirect_to current_user
redirect_to user_path(current_user)
redirect_to url_for([:admin, current_user, :edit])

如果我使用 redirect_to user_path(current_user.id)) 中的对象 ID,则不会发生错误。但是,然后例如url_for 也会中断,因为我不能使用 url_for([@parent.id, @object.id, :edit])(对象不能仅从它们的 ID 派生,而是路径所需要的)。

只有在使用 RSpec 3 和 Rails 4.2.1 的模拟对象时才会发生这种情况。任何帮助都将不胜感激,因为这会导致很多测试现在失败。

【问题讨论】:

    标签: redirect ruby-on-rails-4 rspec-rails rspec3


    【解决方案1】:

    Rspec 3 extracted mocks supportrspec-activemodel-mocks gem 中,因此您可能需要将 rspec-activemodel-mocks 添加到您的 Gemfile 中,以使路由助手的行为符合您的规范中的预期。

    【讨论】:

    • 谢谢。不过,我已经有了那个宝石(否则根本没有路线可以工作)。错误仍然发生... :(
    • 您是否尝试将:to_param 添加到您的mock_model(如mock_model(User, login: User.make_token, to_param: 7))?也许 rails 无法从模拟模型中创建参数,因为预期的实例方法没有被存根。
    • 其实恰恰相反。我的一些初始化序列包括一个“to_param: 1”块,它包含在所有mock_model 调用中。这为我指明了正确的方向。我删除了它。现在我再次遇到有用的测试失败(并且需要找出为什么首先添加它......)。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多