如何测试是否渲染了正确的模板(RSpec Rails)?

How to test whether right template is rendered (RSpec Rails)?

我试图掌握 TDD 的一些概念,在我的 RoR 应用程序中,我有 /about 视图属于 static_pages#about。它在 routes.rb get 'about' => 'static_pages#about' 中定义了路线。到目前为止,一切都在浏览器中运行,但我也想通过 RSpec 对其进行测试。 鉴于

RSpec.describe "about.html.erb", type: :view do
  it "renders about view" do
    render :template => "about"
    expect(response).to render_template('/about')
  end
end

引发错误

Missing template /about with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :......

谢谢!

此规范意义不大 - 视图规范的整个想法是您渲染被测视图,然后编写关于其内容的期望(TDD 中的断言)。视图规范有时对测试复杂视图很有用,但在这种情况下并不是您所需要的。

如果您想测试控制器是否呈现正确的模板,您可以在控制器规范中进行。

require 'rails_helper'
RSpec.describe StaticPagesController, type: :controller do
  describe "GET /about" do
    it "renders the correct template" do
      get :about
      expect(response).to render_template "static_pages/about"
    end
  end
end

虽然这种规范通常没有什么价值 - 您只是在测试 rails 的默认行为,这可以由 feature spec 涵盖,它增加了更多价值:

require 'rails_helper'
RSpec.feature "About page" do
  before do
    visit root_path
  end

  scenario "as a vistior I should be able to visit the about page" do
    click_link "About"
    expect(page).to have_content "About AcmeCorp"
  end
end

请注意,这里我们已经离开了 TDD 的世界,进入了所谓的行为驱动开发 (BDD)。哪个更关心软件的行为,而不是如何完成工作的细节。