Skip to content

Instantly share code, notes, and snippets.

@hack3rvaillant
Last active May 22, 2017 09:12
Show Gist options
  • Save hack3rvaillant/c54014da434bfc4607f0bb1b98fd6aed to your computer and use it in GitHub Desktop.
Save hack3rvaillant/c54014da434bfc4607f0bb1b98fd6aed to your computer and use it in GitHub Desktop.
rspec_cheatsheet WIP

Controllers Specs

#spec/controllers/third_party_elements_controller_spec.rb -fd

require 'rails_helper'

RSpec.describe ThirdPartySitesController, type: :controller do
...
end

Check response status example

describe 'GET #index' do
  it 'returns http success' do
    get :index
    expect(response).to have_http_status(:success)
  end
end

Check creation / update / deletion in database for put, post, patch and delete requests

it 'adds a new record in database' do
  params = { id: 18,
             name: "Pixabay",
             category: "internet",
             kind: "video",
             domain: "https://pixabay.com/en/videos/" }
  expect { post(:create, third_party_site: params, format: :js) }
    .to change { ThirdPartySite.count }.by(1)
end

it 'deletes a record from database' do
        third_party_site # needed to lazy load the third party site
        expect { delete(:destroy, id: third_party_site.id, format: :js) }
          .to change { ThirdPartySite.count }.from(1).to(0)
      end

Check instances variables sent to the view mainly for get requests

# to access the @users variable set in users_controller we need to use assigns(:users) 
it 'lists only active users' do
  get :suspects
  expect(assigns(:users).count).to eq(9)
end

Use a debbugger in your spec with pry: true

it 'lists only active users', pry: true do
  get :suspects
  expect(assigns(:users).count).to eq(9)
end

run your tests in terminal

rspec .spec/controllers/third_party_elements_controller_spec.rb -fd

the -fd flag is for improved readability

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment