【问题标题】:Rspec-rails: Testing if layout includes styles or javascriptsRspec-rails:测试布局是否包含样式或 javascripts
【发布时间】:2011-05-09 08:10:33
【问题描述】:

我想测试我的“style.css”是否链接到我的页面,同时使用某种布局呈现它,例如“application.html.erb”:

所以这是规范:

spec/views/layouts/application.html.erb_spec.rb

  it 'should include styles for screen media' do
    render
    rendered.should have_selector('link',
      :href => '/stylesheets/style.css',
      :media => 'screen',
      :rel => 'stylesheet',
      :type => 'text/css'
    )
  end

我的 application.html.erb 看起来像:

app/views/layouts/application.html.erb

<html>
  <head>
    <meta content="text/html; charset=utf-8" http-equiv="content-type">
    <%= stylesheet_link_tag :style, :media => 'screen' %>
    <%= javascript_include_tag :defaults %>
    <%= csrf_meta_tag %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

当我运行视图规范时,它失败了,因为

<link href="/stylesheets/style.css?1289599022" media="screen" rel="stylesheet" type="text/css">

被渲染,并且

<link rel='stylesheet' type='text/css' media='screen' href='/stylesheets/reset.css'/>

是预期的。

这都是关于文件名后添加的数字“?1289599022”轨道。有关如何测试此功能的任何想法?

【问题讨论】:

标签: ruby-on-rails layout rspec


【解决方案1】:

尝试使用 Rails stylesheet_path() 帮助器...这将为您生成带有时间戳的 URL。

it 'renders a link to the stylesheet' do
  render
  rendered.should have_selector('link',
    :rel => 'stylesheet',
    :media => 'screen',
    :href => stylesheet_path('style')
  )
end

【讨论】:

    【解决方案2】:

    我今天也遇到了同样的问题,非常令人沮丧。我尝试了上面的解决方案,但无法访问 stylesheet_path(我正在使用 rspec 控制器测试,但直接从控制器测试呈现视图)。我尝试包含必要的模块以使其工作,但这只是给了我其他错误。最终,我决定只在测试模式下更改 rails,这样它就不会生成资产时间戳。

    只需编辑您的 test.rb 以包含以下行:

    ENV['RAILS_ASSET_ID'] = ''

    内部

    Testapp::Application.configure 做 ... 结束

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 2010-09-11
      • 1970-01-01
      • 2011-11-16
      • 2011-04-27
      • 2013-12-09
      • 2013-12-28
      相关资源
      最近更新 更多