Filip Bartuzi
Filip Bartuzi

Reputation: 5931

RSpec matcher for request rendering text

Is it possible to examine if get request rendered text?

I know there are hacks like response.body == 'any string' but it does not interest me. I'm just wondering if there is "RSpec™" way to do it.

Having this 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

I would love to be able to call it { is_expected.to render_template(text: 'Hellow')}. It raises:

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

or maybe it { is_expected.to render_template('Hellow')}

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

Is there any RSpec™ way to accomplish it?

Upvotes: 1

Views: 1873

Answers (1)

Kristj&#225;n
Kristj&#225;n

Reputation: 18803

Testing expect(response.body).to eq('Hellow') is totally appropriate.

The reason is_expected.to render_template isn't working is you aren't rendering a template. If your controller omitted an explicit render call, Rails would render the index template for you, and you could test render_template(:index). You could also render template: :foo and then test render_template(:foo) if you wanted to render a nonstandard template. But when you render text: 'Hellow', you aren't using templates; you're explicitly setting the response body to the text you specify.

If you do render a template, and you want to test the content rendered by that template, that's when render_views comes into play, as gotva mentioned. Even then, you'd be checking for content in response.body, as you can see in RSpec's own examples. As your templates get complicated, the controller specs aren't the appropriate place for this and you should start writing view specs using assert_select or something similar.

Upvotes: 2

Related Questions