【问题标题】:Shoulda/Minitest redirect_to { url_helper } not working without hash应该/Minitest redirect_to { url_helper } 在没有哈希的情况下无法工作
【发布时间】:2015-12-31 02:13:46
【问题描述】:

使用 Rails 4.2、Minitest 和 Shoulda...

student_phone_numbers_controller_test.rb

class StudentPhoneNumbersControllerTest < ActionController::TestCase
  context "deleting to remove" do
    context "when the phone number doesn't belong to the student" do
      setup do
        log_in_as(teachers(:schmidt))
        delete :remove,
          format: "js",
          student_id: students(:two).id,
          id: phone_numbers(:one_one).id
      end

      should use_before_action :logged_in_teacher
      should use_before_action :set_student
      should respond_with :redirect
      should redirect_to { student_path students(:two) }
    end
  end
end

一般来说,Shouda 和 Rails 测试的新手,我的代码似乎与 the Minitest documentation for redirect_to 平行。但是,我在运行测试时遇到了这个错误......

$ rake test:controllers
rake aborted!
ArgumentError: wrong number of arguments (0 for 1)

...指向should redirect_to 行。我假设它想要控制器/动作哈希?

以下行按预期工作:

should redirect_to(controller: :students, action: :show) { student_url students(:two) }

...这样...

should redirect_to({}) { student_url students(:two) } 

第一个修复完全是多余的。第二个似乎是多余的。我意识到the source for this method 没有单个参数的默认值。应该吗?

或者,我是否明显遗漏了有关此助手的目的/工作原理的其他内容?

【问题讨论】:

    标签: ruby-on-rails minitest shoulda


    【解决方案1】:

    这实际上是文档中的一个错误,实际上是最近才提出的一个问题:https://github.com/thoughtbot/shoulda-matchers/issues/788。第一个参数是路径的人类可读表示;它被插入到测试的名称中,因此会在您运行测试时显示在输出中。

    所以你可能有类似的东西:

    should redirect_to("the URL for student two") { student_url students(:two) }
    

    希望这会有所帮助。

    【讨论】:

    • 啊……这很有帮助!源代码中显示&amp;block 不是强制性的。我可以在url_or_description 中使用一种格式来允许我使用一个参数执行双重任务吗?只是适用于assert_redirected_to 的东西?
    • 不幸的是,这里的块强制性的。你不能说should redirect_to(student_url(students(:two))),因为student_url 在调用should 时不能立即使用——它需要在测试本身的上下文中使用instance_eval
    • 知道了。非常感谢您花时间回答! :)
    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2016-07-27
    • 2017-07-16
    • 2012-12-21
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多