mardi 18 septembre 2018

RSpec controller test errors within embedded resource

So I was writing tests for my app using responders gem. Here are my routes:

resources :sites do
  resources :pages, shallow: true
end

My PagesController chunk of code:

def create
  respond_with(@page = @site.pages.create(page_params))
end

def find_site
  @site = current_user.sites.find(params[:site_id])
end

And tests that are failing:

sign_in_user
let(:user_2) { create(:user) }
let(:site) { create(:site, user: @user) }
let(:page) { create(:page, site: site, user: @user) }

describe 'POST #create' do
  context 'with valid attributes' do
    it 'associates new page with the site' do
      expect { post :create, params: { page: attributes_for(:page), site_id: site } }.to change(site.pages, :count).by(1)
   end

    it 'redirects to show view' do
      post :create, params: { page: attributes_for(:page), site_id: site }
      expect(response).to redirect_to page_path(assigns(:page))
    end
  end

Errors are following:

1) PagesController POST #create with valid attributes associates new page with the site
  Failure/Error: expect { post :create, params: { page: attributes_for(:page), site_id: site } }.to change(site.pages, :count).by(1)
   expected #count to have changed by 1, but was changed by 0
 # ./spec/controllers/pages_controller_spec.rb:37:in `block (4 levels) in <top (required)>'

 2) PagesController POST #create with valid attributes redirects to show view
 Failure/Error: expect(response).to redirect_to page_path(assigns(:page))

 ActionController::UrlGenerationError:
   No route matches {:action=>"show", :controller=>"pages", :id=>nil}, missing required keys: [:id]
 # ./spec/controllers/pages_controller_spec.rb:42:in `block (4 levels) in <top (required)>'

If I change site.pages in first test to Page - it's actually working.

So I am really confused how to fix this tests and where is the mistake.

Aucun commentaire:

Enregistrer un commentaire