gpt4 book ai didi

ruby-on-rails - Rspec 阻止方法被调用

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:03 26 4
gpt4 key购买 nike

我正在测试用于创建新订单的 Controller 方法(类似电子商务的应用程序)。如果用户存在于系统中,他应该被重定向到 new_user_session_path,否则到 new_order_path。就这么简单。

这是我的orders_controller.rb

def new
if !User.where(phone: params[:phone]).blank? && !user_signed_in?

redirect_to new_user_session_path()
flash[:info] = "Already present"
else
@order = Order.new
@menu = Menu.find(params[:menu_id])
@menu_price = @menu.calculate_price(@menu, params)
end
end

在我的应用中,我需要调用 calculate_price 方法,因为它根据给定的参数计算总价。但在我的测试中,我只想确保重定向是正确的。

现在我收到如下错误(它们源自 Menu.rb 文件,因为调用了 calculate_price):

Front::OrdersController#new redirects user to new order page if user is not present in the system
Failure/Error: menu_price_change = menu_amount.split(",")[1].gsub(" ","").gsub("]",'')

NoMethodError:
undefined method `split' for nil:NilClass

这是我的规范文件:

require 'rails_helper'


describe Front::OrdersController, type: :controller do
describe '#new' do
# Set up dummy menu
let (:menu) { Menu.create() }

it "redirects user to sign up page if user is present in the system" do
user = User.create(name: "Bob", password: "bobspassword", phone: "+7 (903) 227-8874")

get :new, params: { phone: user.phone }
expect(response).to redirect_to(new_user_session_path(phone: user.phone))
end

it "redirects user to new order page if user is not present in the system" do
non_present_phone = "+7 (903) 227-8874"
get :new, params: { phone: non_present_phone, menu_id: menu.id}
expect(response).to redirect_to(new_order_path)
end

end
end

当然我可以提供所有的参数,但是它们的数量相当大,而且,我只是想测试正确的重定向。据我所知,当您想显式测试这些方法时,模拟和潜艇在这种情况下很有用。但就我而言,我想——以某种方式——忽略它们。我怎样才能确保这种行为?

最佳答案

所以你只想测试重定向,当 calculate_price 方法执行时发生的错误打扰了你。你为什么不把那个方法 stub ?您的规范文件可能是这样的:

require 'rails_helper'


describe Front::OrdersController, type: :controller do
describe '#new' do
# Set up dummy menu
let (:menu) { Menu.create() }

# Check this out
before do
allow_any_instance_of(Menu).to receive(:calculate_price)
# or if you need certain value
allow_any_instance_of(Menu).to receive(:calculate_price).and_return(your_value)
end

it "redirects user to sign up page if user is present in the system" do
user = User.create(name: "Bob", password: "bobspassword", phone: "+7 (903) 227-8874")

get :new, params: { phone: user.phone }
expect(response).to redirect_to(new_user_session_path(phone: user.phone))
end

it "redirects user to new order page if user is not present in the system" do
non_present_phone = "+7 (903) 227-8874"
get :new, params: { phone: non_present_phone, menu_id: menu.id}
expect(response).to redirect_to(new_order_path)
end

end
end

关于ruby-on-rails - Rspec 阻止方法被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41791534/

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