如何使用RSpec测试渲染部分

时间:2012-03-30 16:01:09

标签: ruby-on-rails ruby ruby-on-rails-3 rspec

我想根据某些条件测试渲染特定部分。

例如,在模型展示操作视图show.html.erb中,我有:

<% if condition1 %>
 <%=  render :partial => "partial1" %>
<% else %>
 <%=  render :partial => "partial1" %>
<% end %>

我试过了:

response.should render_template("partial_name")

但它告诉它呈现“show”模板

  

期待&lt;“partial1”&gt;但用&lt;“模型/节目渲染,   布局/应用“&GT;

我做错了什么?

7 个答案:

答案 0 :(得分:66)

也试试这个

response.should render_template(:partial => 'partial_name')

答案 1 :(得分:27)

最新的rspec版本建议使用expect语法而不是should

expect(response).to render_template(partial: 'partial_name')

答案 2 :(得分:5)

如果您在控制器中进行测试,则应执行以下操作:

RSpec.describe Users::RegistrationsController, type: :controller do
  describe "GET #new" do
    render_views

    it "render customer partial" do
      get :new
      expect(response).to render_template :new
      expect(response).to render_template(partial: '_new_customer')
    end
  end
end

请注意,我们需要将 render_views 报告为documentation

这是测试是否&#34; _new_customer&#34;部分渲染:

expect(response).to render_template(partial: '_new_customer')

您需要提供具有初始下划线的部分名称。

另外要小心,因为在你的代码中,IF和ELSE语句呈现相同的东西。

答案 3 :(得分:0)

如果在rspec控制器中使用

expect(response).to render_template(partial: 'home/_sector_performance')

答案 4 :(得分:0)

从Rails 5.1开始,this kind of test is discouraged and you should test the controller and the view as a whole

检查受控对象呈现的部分是您不应该测试的实现细节的一部分。

因此,我建议您编写一个请求测试,并检查您的部分相关文本是否存在于响应正文中。

get root_path
expect(CGI.unescape_html(response.body)).to include('Hello World')

答案 5 :(得分:0)

您还可以测试控制器是否推断出需要采取的措施。

require "spec_helper"

describe "model_name/new.html.erb" do
 it "infers the controller path" do
  expect(controller.request.path_parameters["action"]).to eq("new")
 end
end

文档为here

答案 6 :(得分:-3)

如果存在部分渲染的html,则可以选择检查上述解决方案,而不是上述解决方案。 E.g。

response.body.should have_tag("div#foo")