render_template 匹配器

render_template 匹配器用于指定请求渲染给定模板或布局。它委托给 assert_template

它在控制器规格 (spec/controllers) 和请求规格 (spec/requests) 中可用。

注意:对于重定向,请使用 redirect_to(:action => 'new'),而不是 render_template

使用 render_template 和三个可能的选项

给定一个名为“spec/controllers/gadgets_spec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe GadgetsController do
  describe "GET #index" do
    subject { get :index }

    it "renders the index template" do
      expect(subject).to render_template(:index)
      expect(subject).to render_template("index")
      expect(subject).to render_template("gadgets/index")
    end

    it "does not render a different template" do
      expect(subject).to_not render_template("gadgets/show")
    end
  end
end

我运行 rspec spec/controllers/gadgets_spec.rb

那么这些示例应该全部通过。

指定请求渲染给定布局

给定一个名为“spec/controllers/gadgets_spec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe GadgetsController do
  describe "GET #index" do
    subject { get :index }

    it "renders the application layout" do
      expect(subject).to render_template("layouts/application")
    end

    it "does not render a different layout" do
      expect(subject).to_not render_template("layouts/admin")
    end
  end
end

我运行 rspec spec/controllers/gadgets_spec.rb

那么这些示例应该全部通过。

在视图规格中使用 render_template

给定一个名为“spec/views/gadgets/index.html.erb_spec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe "gadgets/index" do
  it "renders the index template" do
    assign(:gadgets, [Gadget.create!])
    render

    expect(view).to render_template(:index)
    expect(view).to render_template("index")
    expect(view).to render_template("gadgets/index")
  end

  it "does not render a different template" do
    expect(view).to_not render_template("gadgets/show")
  end
end

我运行 rspec spec/views

那么这些示例应该全部通过。