测试 Rails 控制器选择布局而不渲染布局

发布于 2024-12-02 11:13:50 字数 181 浏览 5 评论 0原文

我想取消渲染,并且想测试是否选择了某个布局

额外的收获:在测试环境中,该布局文件将不存在

是否有一种聪明的方法来检测控制器是否选择了布局而无需渲染,并且不会触发 ActionView::MissingTemplate 错误?

(这是在 Rails 2.3 应用程序上,但请随意聊天 Rails 3)

i'd like to stub out render and i'd like to test that a certain layout is chosen

bonus catch: in the test env, that layout file will not exist

is there a clever way to detect if the controller has selected a layout without rendering, and without triggering an ActionView::MissingTemplate error?

(this is on a Rails 2.3 app, but feel free to chat rails 3)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

古镇旧梦 2024-12-09 11:13:50

最简单的方法是将布局选择逻辑放入助手中并直接测试助手。无需删除任何内容或伪造渲染。

class MyController < ActionController::Base
  layout :choose_layout

private
  def choose_layout
    if some_thing?
      'this_layout'
    else
      'other_layout'
    end
  end
end

class MyControllerTest < ActionController::TestCase
  test "choose_layout" do
    @controller.stubs(:some_thing? => true)
    assert_equal 'other_layout', @controller.send(:choose_layout)
  end
end

The easiest way to do this is put your layout selection logic in a helper and test the helper directly. No need to stub anything out or fake the rendering.

class MyController < ActionController::Base
  layout :choose_layout

private
  def choose_layout
    if some_thing?
      'this_layout'
    else
      'other_layout'
    end
  end
end

class MyControllerTest < ActionController::TestCase
  test "choose_layout" do
    @controller.stubs(:some_thing? => true)
    assert_equal 'other_layout', @controller.send(:choose_layout)
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文