这是我在RSpec中使用的一种很好的技术,我也想在使用Shoulda和Shoulda上下文的项目中使用它。但我不知道这是否可能。有办法做到这一点吗?
我想要的是:在引用嵌套上下文中的let
子句的外部上下文中定义setup
(before
)块。这样,内部上下文可以配置在外部setup
中引用的值,并且setup
在内部上下文中仍然可以是DRY。
RSpec示例(这个示例很简单——请假设我的真实示例在before
块中有更多我不想重复的代码):
describe Thing do
before do
# Notice that `user` isn't defined here--it's defined in `let` blocks
# in nested contexts below.
login_as user
# Assume there's lots more code here that I would like to keep
# DRY across contexts.
end
context "when logged in as an admin" do
# THIS IS THE MAGIC RIGHT HERE:
let(:user) { Factory(:user, role: "admin") }
it "should ..." ...
end
context "when logged in as a normal user" do
# THIS IS THE MAGIC RIGHT HERE:
let(:user) { Factory(:user) }
it "should ..." ...
end
end
总结一下:我如何使用should上下文和Test::Unit来做到这一点?
我已经尝试过一些没有效果的东西:
def
在每个子文本中重新定义一个方法- CCD_ 8
我发现测试类中的辅助方法对于提取测试之间重复的代码非常有用。像这样:
class MyTest < TestCase
context "when logged in as an admin" do
setup do
do_login Factory(:user, role: "admin")
end
should "..." do
...@user...
end
end
context "when logged in as an admin" do
setup do
do_login Factory(:user)
end
should "..." do
...@user...
end
end
def do_login(user)
login_as user
@user = user
# lots more setup code here...
end
end