Search code examples
ruby-on-railsrspec-rails

Rails controller rendering last template of iteration for all tests


I had controller tests that check that the right template is rendered for varying status codes. They worked.

I am trying to refactor the tests using iteration as follows:

context 'renders multiple views based on status code' do
  VIEW_MAP = {
    404 => 'not_found', 500 => 'server_response', 402 => 'client_response'
  }

  VIEW_MAP.each do |status_code, view|
    retrieve_deal(status_code)
    it 'renders the #{view} template for status code #{status_code}' do
      get :show, params: { id: 'id' }
      expect(response).to render_template(view)
    end
  end
end

where retrieve_deal method mocks an API call with a status code, and sends the response to the controller.

However, the last template ('client_response') is rendered for all the tests. Any ideas where I am going wrong?


Solution

  • I think each iteration needs to be in a context, and:

    retrieve_deal(status_code)
    

    needs to be in something like before.