如何在控制器中测试此代码?我的问题是 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
答案 0 :(得分:1)
你可以控制器测试这个
# 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