【问题标题】:Tests including 'redirect_to' method fail but app works fine. Chapter 9.2.2 of Michael Hartl book (v 3.2)包括“redirect_to”方法的测试失败,但应用程序工作正常。 Michael Hartl 书的第 9.2.2 章 (v 3.2)
【发布时间】:2012-04-21 18:16:24
【问题描述】:

当未登录用户尝试访问用户控制器的编辑或更新操作时,应用应重定向(例如,登录页面或 root_path)。 应用程序运行良好,但对此的测试失败并出现以下错误:

Failure/Error: specify { response.should redirect_to(signin_path) }
Expected response to be a redirect to <http://www.example.com/signin> but was a redirect to <https://www.example.com/users/468>
# ./spec/requests/authentication_pages_spec.rb:69:in `block (6 levels) in <top (required)>'

这里可能有什么问题?怎么调试?

所有代码都在这里:https://github.com/tomek-rusilko/miniatury_katalog_2 失败的测试在这里:https://github.com/tomek-rusilko/miniatury_katalog_2/blob/master/spec/requests/authentication_pages_spec.rb(行:63 和 105)

【问题讨论】:

    标签: ruby-on-rails rspec capybara railstutorial.org


    【解决方案1】:

    终于有时间重温一下了。我从 github 中提取了您的代码并遇到了同样的问题。我将测试缩减为:

    require 'spec_helper'
    
    describe "A non-signed_in user directly issuing PUT to the update action" do
      before { put user_path(7) }
      specify { response.should redirect_to(signin_path) }          
    end
    

    正如您所指出的,控制器代码中的 binding.pry 并没有像我想象的那样停止执行。经过大量无用的挖掘/谷歌搜索,终于在 log/test.log 中注意到:

    Started PUT "/users/7" for 127.0.0.1 at 2012-05-23 16:17:31 -0400
    Processing by UsersController#update as HTML
      Parameters: {"id"=>"7"}
    Redirected to https://www.example.com/users/7
    Filter chain halted as #<Proc:0x00000102201608@/Users/eric_mccullough/ruby/railstutorial/tomek-rusilko-miniatury_katalog_2-e73d795/vendor/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_controller/metal/force_ssl.rb:28> rendered or redirected
    Completed 301 Moved Permanently in 1ms (ActiveRecord: 0.0ms)
       (0.1ms)  rollback transaction
       (0.1ms)  begin transaction
    

    它正在尝试使用 SSL。我的 Rails 教程版本仅在生产中使用 SSL。我从 application_controller.rb 中删除了“force_ssl”,然后所有测试都通过了。我还是 Rails 的新手,甚至没有意识到有日志,但我现在知道了!

    【讨论】:

    • 感谢您向我展示 pry gem。我玩了一下,但我仍然找不到解决方案。看起来测试永远不会到达signed_in_user 方法。我尝试将binding.pry 放置在控制器的各个位置,并且测试一开始只进行一次。命名路由辅助方法和其他方法(如signed_in?current_user)在 pry 命令行中也不可用......我在这里无能为力。
    • 有效!非常感谢您,我已经为此苦苦挣扎了 2 周。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多