Search code examples
ruby-on-railsruby-on-rails-4factory-botrspec-rails

FactoryGirl doesnt save records to the db


I test my destroy and update methods in hotel_controller and Im keep getting ActiveRecord:RecordNotFound error. Heres a screenshot

I think this is coz FactoryGirs doesnt save recods to the db. Help me pls to get things right.

hotels_controller.rb

class HotelsController < ApplicationController
  before_action :signed_in_user, except: [:index, :show, :top5hotels]

...

  def destroy
    @hotel = current_user.hotels.find(params[:id])
    @hotel.destroy
    redirect_to hotels_url
  end  

def update
    @hotel = current_user.hotels.find(params[:id])
    if @hotel.update_attributes!(params[:hotel])
      redirect_to @hotel, notice: "Hotel was successfully updated."
    else
      render "edit"
    end
  end

...

end

factories.rb

    FactoryGirl.define do
      factory :hotel do
        name 'NewHotel'
        star_rating 5
        breakfast false
        room_description 'Room Description'
        price_for_room 500
        user { create(:user) }
        address { create(:address) }
      end

      factory :user do
        sequence(:email) { |n| "user_mail.#{n}@gmail.com" }
        name 'Yuri Gagarin'
        password 'foobar'
        password_confirmation 'foobar'
      end

      factory :rating do
        value 5
        user { create(:user) }
        hotel { create(:hotel) }
      end

      factory :comment do
        body "Heresanytextyouwant"
        user { create(:user) }
        hotel { create(:hotel) }
      end

  factory :address do
    country 'Country'
    state 'State'
    city 'City'
    street 'Street'
  end
end

hotels_controller_spec.rb

require 'spec_helper'

describe HotelsController do

  before { sign_in user, no_capybara: true }

...

    describe "destroy action" do
        it "redirects to index action when hotel is destroyed" do
            hotel = create(:hotel)
            delete :destroy, id: hotel.id
            expect(response).to redirect_to(hotels_url)
        end
    end

describe "update action" do
    it "redirects to the hotel" do
        hotel = create(:hotel)
        put :update, id: hotel.id, hotel: FactoryGirl.attributes_for(:hotel)
        expect(assigns(:hotel)).to be_eq(hotel)
        #expect(response).to render_template('show')
    end
end

end

Solution

  • FactoryGirl IS saving records to db.

    The trouble is the current_user is not the same user that the hotel belongs to, so when you try to retrieve the hotel record it's not found.

    Try changing...

    @hotel = current_user.hotels.find(params[:id])
    

    to...

    @hotel = Hotel.find(params[:id])
    

    And you'll see it works.

    If you want to keep the original code, then in the test you should be doing...

    hotel = create(:hotel, user: current_user)