gpt4 book ai didi

ruby-on-rails - 具有链式方法的 Rspec 测试 Controller

转载 作者:行者123 更新时间:2023-11-28 20:40:37 25 4
gpt4 key购买 nike

如何在我的 Controller 中测试这段代码?我的问题是 wizard_incompleted? 方法

class ApplicantsController < ApplicationController
def index
@applicant = current_user.applicant
@application = @applicant.applications.last


if @application.wizard_incompleted?
# some redirect
end
end
end


describe "GET #index" do

let(:application) { double('application')}

it "redirect to wizard if it is incompleted" do
get :index
allow_any_instance_of(application).to receive(:wizard_incompleted?).and_return(true)
expect(response).to redirect_to(new_applicants_application_path)
end
end

最佳答案

你可以 Controller 测试这个

# app/controllers/applicants_controller.rb
class ApplicantsController < ApplicationController
def index
@applicant = current_user.applicant
@application = @applicant.applications.last
redirect_to "/" if @application.wizard_incompleted?
end
end

像这样

# spec/controllers/applicants_controller_spec.rb
require "spec_helper"

describe ApplicantsController, type: :controller do
it "#index" do
last_application = double(:last_application, wizard_incompleted?: true)
applications = double(:applications, last: last_application)
applicant = double(:applicant, applications: applications)
current_user = double(:current_user, applicant: applicant)
expect(controller).to receive(:current_user).and_return(current_user)
expect(current_user).to receive(:applicant).and_return(applicant)
expect(applicant).to receive(:applications).and_return(applications)
expect(applications).to receive(:last).and_return(last_application)
expect(last_application).to receive(:wizard_incompleted?).and_return(true)
get :index
expect(assigns(:applicant)).to eq applicant
expect(assigns(:application)).to eq last_application
expect(response).to redirect_to "/"
end
end

关于ruby-on-rails - 具有链式方法的 Rspec 测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34908367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com