如何在shoulda上下文中覆盖设置值,如RSpec`let`?

时间:2013-08-14 16:57:54

标签: ruby shoulda

这是我使用RSpec的一个很好的技术,我也想在使用Shoulda和Shoulda-context的项目中使用。但我不知道是否可能。有没有办法做到这一点?

我想要的是:在外部上下文中定义setupbefore)块,该块引用嵌套上下文中的let子句。这样,内部上下文可以配置外部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

总结一下:我怎么能用shoulda-context和Test :: Unit?

来做到这一点

我已尝试过的一些不起作用的事情:

  • def重新定义每个子上下文中的方法。
  • 每个子上下文中
  • before_should

1 个答案:

答案 0 :(得分:2)

我发现测试类中的辅助方法对于拉出测试之间重复的代码非常有用。像这样:

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