如何重构 RSpec 文件中的辅助方法?
我正在使用 Ruby on Rails 3.1.0 和 rspec-rails 2 gem。我想重构以下代码(我故意省略了一些代码,并给出了有意义的名称以突出结构):
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
为了重构上述代码,我可以\应该做什么?
PS:我尝试在外部模块(名为Sample
)中提取辅助方法,但是,例如与D1_C1_Method_1< /code> 方法(包含RoR
session
),当我运行规范文件时,出现以下错误:
Failure/Error: session.should be_nil
NameError:
undefined local variable or method `session' for Sample:Module
I am using Ruby on Rails 3.1.0 and the rspec-rails 2
gem. I would like to refactor the following code (I have intentionally omitted some code and I have given meaningful names in order to highlight the structure):
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
What can\should I make in order to refactor the above code?
P.S.: I have tried to extract helper methods in an external module (named Sample
) but, for example relating to the D1_C1_Method_1
method (that contains the RoR session
), I get the following error when I run the spec file:
Failure/Error: session.should be_nil
NameError:
undefined local variable or method `session' for Sample:Module
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过将助手作为外部模块包含在内?
现在是助手:
Have you tried to include the helpers as an external module?
And now the helper: