【问题标题】:How do I test the title of a page from an RSpec view spec?如何从 RSpec 视图规范测试页面标题?
【发布时间】:2010-10-22 21:50:16
【问题描述】:

我正在用Rails 3学习RSpec 2。为了在每个页面的布局中设置标签的内容,我有一个助手可以用来设置标题然后返回:

def page_title(subtitle=nil)
  if @title.nil?
    @title = ["Site Name"]
  end

  unless subtitle.nil?
    @title << subtitle
  end

  @title.reverse.join " - "
end

从返回标题的布局和设置标题的各个视图都调用助手。现在,我想在视图规范中测试标题设置是否正确。由于没有呈现布局,我决定从规范中调用 page_title 并检查返回值是否符合我的预期。但是,这不起作用,并且总是只返回“站点名称”。我该怎么办?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec title rspec2


    【解决方案1】:

    要检查视图规范中页面的标题,请尝试:

    require "spec_helper"
    
    describe "controller/view.html.erb" do
      it "renders page title with 'Title | MySite'" do
        render template: "controller/view", layout: "layouts/application"
        rendered.should have_selector("title", text: "Title | MySite")
      end
    end
    

    因为渲染是在控制器外部调用的,所以需要告知布局。

    【讨论】:

      【解决方案2】:

      我不确定这是否是您的意思,但您可以直接测试布局:

      require 'spec_helper'
      include ApplicationHelper
      
      describe "layouts/application" do
        it "should add subtitle to page title" do
          page_title("Subtitle")
          render
          rendered.should have_selector('title:contains("Subtitle - Site Name")')
        end
      end
      

      编辑

      您还可以测试视图中是否调用了page_title 方法:

      describe "mycontroller/index" do
        it "should set subtitle" do
          view.should_receive(:page_title).with("Subtitle")
          render
        end
      end
      

      或者您可以使用带有render_views 的控制器测试:

      describe Mycontroller do
        render_views
        it "sets the page title" do
          get :index
          response.body.should contain("Subtitle - Site Name")
        end
      end
      

      【讨论】:

      • 谢谢,但这不是我想要的。我正在尝试通过检查 page_title 的输出到我希望该页面返回的内容来测试视图是否正确设置了标题(通过调用 page_title)。就像,每个视图都会有所不同。
      • 嗯,这不是我最初想要的,但我决定从控制器规范中测试它。谢谢!
      • 谢谢,这个回复帮助我理解了布局可以像另一个视图一样进行测试。
      • have_title matcher 也可以用于 capybara/rspec
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多