【问题标题】:RSpec matcher for request rendering text用于请求呈现文本的 RSpec 匹配器
【发布时间】:2015-10-28 12:52:02
【问题描述】:

是否可以检查get请求是否呈现文本?

我知道有像response.body == 'any string' 这样的黑客,但我不感兴趣。我只是想知道是否有“RSpec™”方法来做到这一点。

拥有这个 rspec:

RSpec.describe MyController, type: :controller do
  controller do
    def index
      render text: 'Hellow'
    end
  end

  describe 'rendering' do
    subject { get :index }
    it { is_expected.to render_template(text: 'Hellow')}
  end
end

我希望能够致电it { is_expected.to render_template(text: 'Hellow')}。它提出:

 Failure/Error: it { is_expected.to render_template(text: 'Hellow') }
 ArgumentError:
   Unknown key: :text. Valid keys are: :layout, :partial, :locals, :count, :file

或者it { is_expected.to render_template('Hellow')}

 Failure/Error: it { is_expected.to render_template('Hellow') }
   expecting <"Hellow"> but rendering with <[]>

是否有任何 RSpec™ 方法来完成它?

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 testing rspec


【解决方案1】:

测试expect(response.body).to eq('Hellow') 是完全合适的。

is_expected.to render_template 不起作用的原因是您没有渲染模板。如果您的控制器省略了显式的render 调用,Rails 将为您呈现index 模板,您可以测试render_template(:index)。如果你想渲染一个非标准的模板,你也可以render template: :foo 然后测试render_template(:foo)。但是当你render text: 'Hellow' 时,你没有使用模板;您将响应正文明确设置为您指定的文本。

如果您确实渲染了一个模板,并且您想测试由该模板渲染的内容,那就是render_views 发挥作用的时候,就像gotva mentioned。即便如此,您仍会检查 response.body 中的内容,正如您在 RSpec 自己的示例中看到的那样。随着您的模板变得复杂,控制器规范不适用于此,您应该开始使用assert_select 或类似的东西编写view specs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多