【问题标题】:How to override setup values, like RSpec `let`, in shoulda contexts?如何在应该上下文中覆盖设置值,例如 RSpec `let`?
【发布时间】:2013-08-14 16:57:53
【问题描述】:

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

我想要的是:在外部上下文中定义一个 setup (before) 块,该块在嵌套上下文中引用 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 在每个子上下文中。

【问题讨论】:

    标签: ruby shoulda


    【解决方案1】:

    我发现测试类中的辅助方法对于提取在测试之间重复的代码很有用。像这样:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 1970-01-01
      • 2014-01-19
      • 2021-12-20
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      相关资源
      最近更新 更多