gpt4 book ai didi

ruby-on-rails - 如何重构 RSpec 文件中的辅助方法?

转载 作者:数据小太阳 更新时间:2023-10-29 08:05:49 24 4
gpt4 key购买 nike

我正在使用 Ruby on Rails 3.1.0 和 rspec-rails 2gem。我想重构下面的代码(我有意省略了一些代码,并且为了突出结构我给出了有意义的名字):

describe "D1" do
# Helper method
def D1_Method_1
...
end

context "C1" do
# Helper methods
def D1_C1_Method_1
session.should be_nil # Note: I am using the RoR 'session' hash
D1_Method_1 # Note: I am calling the 'D1_Method_1' helper method
...
end

def D1_C1_Method_2
...
end


it "I1" do
D1_Method_1
...
end

it "I2" do
...
D1_C1_Method_1
D1_C1_Method_2
end
end

context "C2" do
# Helper methods
def D1_C2_Method_1
...
end

def D1_C2_Method_2
...
end


it "I1" do
D1_Method_1
...
end

it "I2" do
...
D1_C2_Method_1
D1_C2_Method_2
end
end
end

为了重构上述代码,我可以\应该做什么?

P.S.:我试图在外部模块(名为 Sample)中提取辅助方法,但是,例如与 D1_C1_Method_1 方法(包含 RoR session),运行规范文件时出现以下错误:

Failure/Error: session.should be_nil
NameError:
undefined local variable or method `session' for Sample:Module

最佳答案

您是否尝试过将助手作为外部模块包含在内?

require 'path/to/my_spec_helper'

describe "D1" do
include MySpecHelper
...
end

现在是助手:

# my_spec_helper.rb
module MySpecHelper
def D1_C1_Method_1
session.should be_nil
...
end
end

关于ruby-on-rails - 如何重构 RSpec 文件中的辅助方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7615268/

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