【问题标题】:FactoryGirl doesnt save records to the dbFactoryGirl 不将记录保存到数据库
【发布时间】:2014-08-26 11:57:57
【问题描述】:

我在 hotel_controller 中测试了我的销毁和更新方法,但我不断收到 ActiveRecord:RecordNotFound 错误。 Heres a screenshot

我认为这是因为 FactoryGirs 不会将记录保存到数据库。请帮我把事情做好。

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 factory-bot rspec-rails


    【解决方案1】:

    FactoryGirl 正在将记录保存到数据库。

    问题是current_user不是酒店所属的同一用户,所以当你尝试检索酒店记录时没有找到。

    尝试改变...

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

    到...

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

    你会看到它有效。

    如果你想保留原始代码,那么在测试中你应该做的......

    hotel = create(:hotel, user: current_user)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多