ruby-on-rails - 如何测试是否呈现正确的模板(RSpec Rails)?

标签 ruby-on-rails rspec rspec-rails

我试图掌握 TDD 的一些概念,在我的 RoR 应用程序中,我有属于 static_pages#about 的/about View 。它在 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, :......

谢谢!

最佳答案

这个规范没有什么意义—— View 规范的整个想法是你渲染被测 View ,然后写下关于它的内容的期望(用 TDD 说的断言)。 View 规范有时对于测试复杂的 View 很有用,但在这种情况下不是您所需要的。

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

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

虽然这种规范通常没有什么值(value)——你只是在测试 rails 的默认行为,这可以通过 feature spec 来覆盖。这增加了更多值(value):
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)。哪个更关心软件的行为,而不是它如何完成工作的细节。

关于ruby-on-rails - 如何测试是否呈现正确的模板(RSpec Rails)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36744267/

相关文章:

ruby-on-rails - ActionView::Template::Error(不兼容的字符编码:UTF-8 和 ASCII-8BIT)

ruby-on-rails - 运行 rake 任务时如何跳过 Rails 初始值设定项的加载?

ruby-on-rails - 如何登录功能规范

SQL查询数组在数组字段中的位置

ruby-on-rails - 带有分类器 gem 的无效编码符号

ruby-on-rails - 带有 Zeus 的 RSpec 3.1,我应该在 spec_helper 中要求 'rspec/rails' 吗?

mysql - spork/guard 重载模式

rspec - 如何在 Rspec/Capybara 中为断言指定失败消息

ruby-on-rails - Rspec 无法在 ubuntu 上运行

ruby-on-rails - rspec not_to 从不按预期行为改变