Home > Software design >  How should i test controller with jbuilder views?
How should i test controller with jbuilder views?

Time:04-26

this is my controller

class NewsController < ApplicationController 
    def show 
        @news = News.find_by id: params[:id]
    end
 end

this is views

json.extract! @news ,:id, :title , :content , :created_at , :updated_at
json.image @news.images do |image| 
    json.url url_for(image)
  end

what is right way of testing this controller and views. I'am new into testing so i'am little bit frustrated with this

CodePudding user response:

You can verify the status and the json result you are expecting

it "should have a 200 code" do
  get :show, params: { id: 1 }, format: :json
  expect(response.status).to eq 200
  expect(response.body).to eq expected_json
end

Refer this article for more info

CodePudding user response:

The recommended way to test controllers is with request specs.

https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec

RSpec.describe 'News', type: :request do
  describe 'GET /news/:id' do
    context 'when found' do
      let(:news) { News.create(title: 'The News', content: 'Super relevant')}
      before { get news_path(news) } # runs before each spec

      it { expect(response).to have_http_status :ok }
      it { expect(response.body).to include news.title }                    # good enough
      it { expect(JSON.parse(response.body)[:content]).to eq news.content } # or be precise
      it 'has some images' do
        expect(JSON.parse(response.body)[:images]).to be_present
      end
    end

    context 'when not found' do
      before { get news_path(999) } 

      it { expect(response).to have_http_status :not_found }
    end
  end
end

It is hard to describe the right way to test. Test for important information only, you don't want to rewrite your test every time you change your view. If you have url parameters that would change the rendered view, test for that.

  • Related