微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails-3 – Rails 3 Rspec 2:测试content_for

我正在运行Rails 3.1.1,RSpec 2.7.0和HAML 3.1.3.

我有以下视图文件

应用程序/视图/布局/ application.html.haml

!!!
%html
  %head
    %title Test
    = stylesheet_link_tag "application"
    = javascript_include_tag "application"
    = csrf_Meta_tags

  %body
    = content_for?(:content) ? yield(:content) : yield

应用程序/视图/布局/ companies.html.haml

- content_for :content do
  #main
    = yield :main
  #sidebar
    = yield :sidebar

= render :template => 'layouts/application'

应用程序/视图/公司/ index.html.haml

- content_for :main do
  %h1 MainHeader
- content_for :sidebar do
  %h1 SidebarHeader

和以下spec文件

规格/视图/公司/ index_spec.rb

require 'spec_helper'

describe 'companies/index.html.haml' do

  it 'should show the headers' do
    render
    rendered.should contain('MainHeader')
    rendered.should contain('SidebarHeader')
  end

end

当我运行RSpec,我得到以下错误

1) companies/index.html.haml should show the headers
   Failure/Error: rendered.should contain('MainHeader')
     expected the following element's content to include "MainHeader":
   # ./spec/views/companies/index_spec.rb:7:in `block (2 levels) in <top (required)>'

起初,我认为在渲染视图文件时,RSpec在某种程度上缺少content_for块.但是,我无法在RSpec的github存储库中找到与之相关的任何问题,所以我不知道这里是谁负责的.

一个(最近)的解决方案,我发现是在http://www.dixis.com/?p=571.但是,当我尝试建议的代码

view.instance_variable_get(:@_content_for)

它返回零.

>有没有办法测试content_for在视图规格?
>有没有更好的方法来构建我的布局文件,这样我实际上可以测试它们,并仍然达到相同的最终结果?

解决方法

使用Rspec 2与Rails 3,为了写入content_for的使用的查看规范,请执行以下操作:
view.content_for(:main).should contain('MainHeader')
# instead of contain() I'd recommend using have_tag (webrat)
# or have_selector (capybara)

附:认情况下,content_for(…)块的值为空字符串,因此如果要
写出specs显示content_for(:main)没有被调用的情况,使用:

view.content_for(:main).should be_blank

您的规格可以写成:

it "should show the headers" do
  render
  view.content_for(:main).should contain('MainHeader')
  view.content_for(:side_header).should contain('SidebarHeader')
end

这样你的规格就可以准确地显示你的观点,而不管任何布局.对于视图规范,我认为隔离测试是合适的.编写查看规格总是有用吗?这是个开放的问题.

相反,如果要编写显示用户标记提供的功能,那么您将需要请求规范或黄瓜功能.第三个选项将是包含视图的控​​制器规范.

附:如果您需要指定直接输出一些标记的视图,并将其他标记委托给content_for(),则可以这样做:

it "should output 'foo' directly,not as a content_for(:other) block" do
   render
   rendered.should contain('foo')
   view.content_for(:other).should_not contain('foo')
end
it "should pass 'bar' to content_for(:other),and not output 'bar' directly" do
   render
   rendered.should_not contain('bar')
   view.content_for(:other).should contain('bar')
end

这可能是多余的,但我只是想显示render()填充渲染和view.content_for. “呈现”包含视图直接生成的任何输出. “view.content_for()”会查看通过content_for()委派的视图的任何内容.

原文地址:https://www.jb51.cc/ruby/273289.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐