我在hotel_controller中测试我的destroy和update方法,并且我一直收到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
答案 0 :(得分:1)
FactoryGirl IS将记录保存到db。
问题是current_user
与酒店所属的用户不同,所以当您尝试检索酒店记录时,找不到它。
尝试更改......
@hotel = current_user.hotels.find(params[:id])
为...
@hotel = Hotel.find(params[:id])
你会发现它有效。
如果你想保留原始代码,那么你应该在测试中......
hotel = create(:hotel, user: current_user)