用于回调after_save的Rspec控制器测试

时间:2014-12-19 20:26:51

标签: ruby-on-rails post rspec callback controllers

我正在尝试测试是否在我的控制器中发布到创建方法会触发我使用after_save定义的回调

这里是发布到

的控制器方法
def create
@guest = Guest.new(guest_params)
@hotel = Hotel.find(visit_params[:hotel_id])

#set visit local times to UTC
@visit= Visit.new(visit_params)
@visit.checked_out_at = (DateTime.now.utc + visit_params[:checked_out_at].to_i.to_i.days).change(hour: @visit.hotel.checkout_time.hour)
@visit.checked_in_at = Time.now.utc
#@visit.user_id = current_user.id
@self_serve = (params[:self_serve] && params[:self_serve] == "true")
if @guest.save
  @visit.guest_id = @guest.id
  if @visit.save
    if @self_serve
      flash[:notice] = "#{@visit.guest.name}, you have successfully checked in!."
      redirect_to guest_checkin_hotel_path(@visit.hotel)
    else
      flash[:notice] = "You have successfully checked in #{@visit.guest.name}."
      redirect_to hotel_path(@visit.hotel)
    end
  else
    render "new"
  end
else
  render "new"
end
end

这是我的spec / controllers / guests_controller_spec.rb测试失败

RSpec.describe GuestsController, :type => :controller do
describe "#create" do
    let!(:params) do { name: "John Smith", mobile_number: "9095551234" } end
    context "when new guest is saved" do
        it "triggers create_check_in_messages callback" do
            post :create, params
            expect(response).to receive(:create_check_in_messages)
        end
    end
end
end

这是我的模型/关注/ visit_message.rb回调文件

module VisitMessage
  extend ActiveSupport::Concern

  included do
    after_save :create_check_in_messages
  end

  def create_check_in_messages
   . . .
  end
end

以下是运行&rs; rspec spec / controllers / guests_controller_spec.rb'

时的失败消息
1) GuestsController#create when new guest is saved triggers create_check_in_messages callback
 Failure/Error: post :create, params
 ActionController::ParameterMissing:
   param is missing or the value is empty: guest
 # ./app/controllers/guests_controller.rb:63:in `guest_params'
 # ./app/controllers/guests_controller.rb:10:in `create'
 # ./spec/controllers/guests_controller_spec.rb:36:in `block (4 levels) in <top (required)>'

我一直在搜索堆栈溢出而没有运气。我感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

我假设控制器中的guest_params方法看起来像这样:

def guest_params
    params.require(:guest).permit(....)
end

如果是这种情况,您需要在测试用例中更新POST调用:

post :create, {guest: params}

另一方面,您的控制器不必要地膨胀。我会阅读使用相关模型来简化您的代码,特别是使用accepts_nested_attributes_for

http://guides.rubyonrails.org/association_basics.html#detailed-association-reference http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html