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

Mar*_*cis 5 rspec ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

引发错误

Missing template /about with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :......
Run Code Online (Sandbox Code Playgroud)

谢谢!

max*_*max 4

这个规范没有什么意义——视图规范的整体思想是渲染被测试的视图,然后编写关于其内容的期望(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
Run Code Online (Sandbox Code Playgroud)

尽管这种规范通常没有什么价值 - 您只是测试 Rails 的默认行为,这可以通过增加更多价值的功能规范来涵盖:

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
Run Code Online (Sandbox Code Playgroud)

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