如何“筑巢”?或“组”测试::单元测试?

发布于 2024-11-06 05:10:19 字数 242 浏览 1 评论 0原文

RSpec 有:

describe "the user" do
  before(:each) do
    @user = Factory :user
  end

  it "should have access" do
    @user.should ...
  end
end

您如何将这样的测试与 Test::Unit 分组?例如,在我的控制器测试中,我想在用户登录和无人登录时测试控制器。

RSpec has:

describe "the user" do
  before(:each) do
    @user = Factory :user
  end

  it "should have access" do
    @user.should ...
  end
end

How would you group tests like that with Test::Unit? For example, in my controller test, I want to test the controller when a user is signed in and when nobody is signed in.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

爱人如己 2024-11-13 05:10:19

您可以通过课程实现类似的目标。可能有人会说这太可怕了,但它确实允许您在一个文件中分离测试:

class MySuperTest < ActiveSupport::TestCase
  test "something general" do
    assert true
  end

  class MyMethodTests < ActiveSupport::TestCase

    setup do
      @variable = something
    end

    test "my method" do
      assert object.my_method
    end
  end
end

You can achieve something similar through classes. Probably someone will say this is horrible but it does allow you to separate tests within one file:

class MySuperTest < ActiveSupport::TestCase
  test "something general" do
    assert true
  end

  class MyMethodTests < ActiveSupport::TestCase

    setup do
      @variable = something
    end

    test "my method" do
      assert object.my_method
    end
  end
end
笑脸一如从前 2024-11-13 05:10:19

据我所知,Test::Unit 不支持测试上下文。但是,gem contest 添加了对上下文块的支持。

Test::Unit, to my knowledge, does not support test contexts. However, the gem contest adds support for context blocks.

一杯敬自由 2024-11-13 05:10:19

应该 https://github.com/thoughtbot/shoulda 虽然看起来他们现在已经创建了上下文- 相关代码放入单独的 gem 中: https://github.com/thoughtbot/shoulda-context

Shoulda https://github.com/thoughtbot/shoulda although it looks like they've now made the context-related code into a separate gem: https://github.com/thoughtbot/shoulda-context

风苍溪 2024-11-13 05:10:19

使用 shoulda-context

在您的 Gemfile 中:

gem "shoulda-context"

以及在您的测试中您可以执行以下操作的文件(请注意 should 而不是 test

class UsersControllerTest < ActionDispatch::IntegrationTest
  context 'Logged out user' do
    should "get current user" do
      get api_current_user_url

      assert_response :success
      assert_equal response.body, "{}"
    end
  end
end

Using shoulda-context:

In your Gemfile:

gem "shoulda-context"

And in your test files you can do things like (notice the should instead of test:

class UsersControllerTest < ActionDispatch::IntegrationTest
  context 'Logged out user' do
    should "get current user" do
      get api_current_user_url

      assert_response :success
      assert_equal response.body, "{}"
    end
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文