Skip to content

Instantly share code, notes, and snippets.

@marciofmjr
Last active July 16, 2019 01:29
Show Gist options
  • Save marciofmjr/949536c8fe3abdeddcdf2204798f3a34 to your computer and use it in GitHub Desktop.
Save marciofmjr/949536c8fe3abdeddcdf2204798f3a34 to your computer and use it in GitHub Desktop.

Controllers

O que o controller faz ?

  • Recebe requisições (com/sem autenticação)
  • Manipula Models
  • Cria respostas
    • Renderizando um template
    • Respondendo com um formato solicitado (json)
    • Redirecionando para outra rota

Generate

rails g rspec:controller ads

Config

# spec/rails_helper.rb

RSpec.configure do |config| 

    #Devise
    config.include Devise::Test::ControllerHelpers, :type => :controller
    
end

Examples

require 'rails_helper'

RSpec.describe AdsController, type: :controller do

    describe 'as guest' do
        
        context '#index' do
            
            # testando requisição 'não autenticada'
            it 'responds successfully' do
                get :index
                expect(response).to be_success
            end
            
            # testando pelo status
            it 'responds a 200 response' do
                get :index
                expect(response).to have_http_status(200)
            end
            
        end
        
        context '#show' do
            
            # testando erro ao acessar página que
            # precisa de login, mas não esta logado
            it 'responds a 302 response (not authorized)' do
                get :show, params: {id: 1}
                expect(response).to have_http_status(302)
            end
            
        end
    
    end
    
    describe "as logged user" do
        
        before do
            @user = create(:user)
            @ad = create(:ad)
            sign_in @user
        end
        
        context '#index' do
            # testando com login
            it 'responds a 200 response with login' do
                get :show, params: {id: @ad.id}
                expect(response).to be_success
            end
        end
        
        context '#create' do
            # testando post
            it 'with valid attributes' do
                ad_params = attributes_for(:ad)
                expect {
                    post :create, params: {ad: ad_params}
                }.to change(Ad, :count).by(1)
            end
        end
        
    
    end
    
    # testando notice
    it 'flash notice' do
        expect(flash[:notice]).to match(/successfully created/)
    end
    
    # testando content-type
    it 'content-type' do
        post :create, format: json, params: {ad: ad_params}
        expect(response.content_type).to eq('application/json')
    end
    

end

Instalação

# Gemfile
group :development, :test do
  gem 'rspec-rails', '~> 3.7'
end

Setup

rails generate rspec:install
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment