2011-05-08 106 views
20

RSpec的有:你如何“嵌套”或“组”测试::单元测试?

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

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

你会如何组测试,如与测试::单位?例如,在我的控制器测试中,我想在用户登录时以及没有人登录时测试控制器。据我所知,

回答

6

不支持测试上下文。但是,the gem contest添加了对上下文块的支持。

+9

在试图挽救某人15分钟的调试时,竞赛宝石已过时,并且不适用于我的Rails 4应用程序。 – AndrewJM 2015-11-02 19:43:15

+2

Gem无法在Rails 5.2上运行,请参阅https://github.com/citrusbyte/contest/issues/9 – Dorian 2017-12-20 17:21:50

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 
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