【问题标题】:How do I stub a path generating method in Rails?如何在 Rails 中存根路径生成方法?
【发布时间】:2012-11-30 12:02:17
【问题描述】:

我正在编写一个视图规范,它呈现一个包含该行的视图(在 haml 中):

=link_to new_post_path

但规范失败:

ActionController::RoutingError: No route matches {:action=>"new", :controller=>"post"}

我正在尝试存根 new_post_path 方法,因为它实际上对视图规范并不重要,但没有任何运气。

在我的规范中,我尝试了以下两种变体,但没有任何运气:

           stub!(:new_post_path).and_return("this path isn't important")
controller.stub!(:new_post_path).and_return("this path isn't important")

【问题讨论】:

    标签: ruby-on-rails-3 rspec stubbing


    【解决方案1】:

    如果您不是在视图规范中,但发现自己需要存根路径助手,则以下语法适用于 Rails 4.2.5;你需要receive_message_chain 来代替这里描述的:

    https://github.com/rspec/rspec-mocks/issues/1038

    也就是说:

    allow(Rails.application).to receive_message_chain(:routes, :url_helpers, :new_post_path).and_return("this path isn't important")

    【讨论】:

    • 或者你可以像我上面的回答那样存根视图而不是存根 Rails.application
    • 如果你在一个视图规范中,那就行了(诚然,这是最初的问题),但我正在努力解决的情况并非如此。我会更新我的答案以反映这一点。
    【解决方案2】:

    方法new_post_path来自Rails.application.routes.url_helpers模块。您需要存根该模块上的方法

    Rails.application.routes.url_helpers.stub(:new_post_path).and_return("this path isn't important")
    

    【讨论】:

    • 谢谢,事实证明我的错误实际上是在其他地方,但你确实帮助我找出了如何存根。
    • 这仅适用于我在我看来使用Rails.application.routes.url_helpers.new_host_path 而不是普通的new_host_path 的情况。我正在使用 rspec 3.2 语​​法allow(Rails.application.routes.url_helpers).to receive(:new_host_path).and_return("/")
    • @ryan2johnson9 如果您想通了,您介意发布您的解决方案吗?我也有同样的问题。
    【解决方案3】:
    allow(view).to receive(:new_post_path).and_return("this path isn't important")
    

    这是 rspec 3.2 语​​法

    我猜旧的语法应该是

    view.stub(:new_post_path).and_return("this path isn't important")
    

    【讨论】:

    • 感谢分享您的修复。
    • 我发现这适用于 RSpec 3.5。 view.stubs(:new_post_path).returns("this path isn't important")
    猜你喜欢
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多