21

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.

danneu
  • 9,244
  • 3
  • 35
  • 63

4 Answers4

11

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
dizzy42
  • 4,826
  • 2
  • 15
  • 8
6

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

Matchu
  • 83,922
  • 18
  • 153
  • 160
  • 15
    In an attempt to save someone a 15 minutes of debugging, the contest gem is out of date and does not work with my Rails 4 application. – AndrewJM Nov 02 '15 at 19:43
  • 4
    Gem doesn't work on Rails 5.2 either, see https://github.com/citrusbyte/contest/issues/9 – Dorian Dec 20 '17 at 17:21
3

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

Jamie Cobbett
  • 339
  • 2
  • 4
2

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
Dorian
  • 7,749
  • 4
  • 38
  • 57
Dorian
  • 22,759
  • 8
  • 120
  • 116