默认情况下视图被存根
默认情况下,控制器规范使用一个渲染空字符串的模板来存根视图,而不是应用程序中的视图。这允许您指定一个动作应该尝试渲染哪个视图模板,无论该模板是否编译干净。
注意:与 rspec-rails-1.x 不同,真实的模板必须存在。
期望由控制器动作渲染的模板(通过)
给定一个名为“spec/controllers/widgetscontrollerspec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe WidgetsController, type: :controller do
describe "index" do
it "renders the index template" do
get :index
expect(response).to render_template("index")
expect(response.body).to eq ""
end
it "renders the widgets/index template" do
get :index
expect(response).to render_template("widgets/index")
expect(response.body).to eq ""
end
end
end
当我运行`rspec spec`
然后这些示例应该全部通过。
期望一个没有被控制器动作渲染的模板(失败)
给定一个名为“spec/controllers/widgetscontrollerspec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe WidgetsController, type: :controller do
describe "index" do
it "renders the 'new' template" do
get :index
expect(response).to render_template("new")
end
end
end
当我运行`rspec spec`
然后输出应该包含“1 个示例,1 个失败”。
期望当运行时更改视图路径时,空模板可以渲染(通过)
给定一个名为“spec/controllers/thingscontrollerspec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe ThingsController, type: :controller do
describe "custom_action" do
it "renders an empty custom_action template" do
controller.prepend_view_path 'app/views'
controller.append_view_path 'app/views'
get :custom_action
expect(response).to render_template("custom_action")
expect(response.body).to eq ""
end
end
end
给定一个名为“app/controllers/things_controller.rb”的文件,其中包含
class ThingsController < ActionController::Base
layout false
def custom_action
end
end
给定一个名为“app/views/things/custom_action.html.erb”的文件,其中包含
当我运行`rspec spec`
然后这些示例应该全部通过。
期望当运行时更改视图路径时,模板可以渲染真实的模板,使用`render_views`
给定一个名为“spec/controllers/thingscontrollerspec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe ThingsController, type: :controller do
render_views
it "renders the real custom_action template" do
controller.prepend_view_path 'app/views'
get :custom_action
expect(response).to render_template("custom_action")
expect(response.body).to match(/template for a custom action/)
end
end
当我运行`rspec spec`
然后这些示例应该全部通过。