gpt4 book ai didi

rspec - 不同 rspec 上下文中的代码重用

转载 作者:行者123 更新时间:2023-12-04 16:47:39 27 4
gpt4 key购买 nike

我正在尝试在 rails Controller 规范中重用一些通用代码。我对管理员用户和普通用户有不同的上下文。但是,对于特定操作,大部分行为是相同的,因此我尝试将这种常见行为提取到辅助函数中:

describe SomeController do
def common_get_new
# common stuff
end

context "regular users" do
describe "GET new" do
common_get_new
end
end

context "admin users" do
describe "GET new" do
common_get_new
end
end
end

这给了我错误:

undefined local variable or method `common_get_new'



我究竟做错了什么?

最佳答案

您是否尝试过使用 Shared Examples ?

describe SomeController do
shared_examples_for "common_get_new" do
# common stuff
end

context "regular users" do
describe "GET new" do
it_should_behave_like "common_get_new"
end
end

context "admin users" do
describe "GET new" do
it_should_behave_like "common_get_new"
end
end
end

取决于您的 common_get_new您问题中的方法,为了简单地摆脱您的错误,您可以将该方法放入 规范/支持/实用程序.rb ,或者按照@Chris Heald 的建议进行操作,并在文件顶部定义方法。

关于rspec - 不同 rspec 上下文中的代码重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14061651/

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