你如何“嵌套”或“分组”测试::单元测试?

问题描述 投票:20回答:4

RSpec有:

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

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

你会如何用Test :: Unit对这样的测试进行分组?例如,在我的控制器测试中,我想在用户登录时以及没有人登录时测试控制器。

ruby-on-rails ruby testunit
4个回答
6
投票

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


10
投票

你可以通过类来实现类似的东西。可能有人会说这很糟糕,但它确实允许你在一个文件中分开测试:

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

3
投票

应该https://github.com/thoughtbot/shoulda虽然看起来他们现在已经将与上下文相关的代码变成了一个独立的宝石:https://github.com/thoughtbot/shoulda-context


1
投票

使用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
© www.soinside.com 2019 - 2024. All rights reserved.