rails 集成测试中的多个用户

Multiple users in a rails integration test

我正在寻找如何对需要 2 个用户的流程进行集成,其中您不能按顺序跳转。

User A does 1
User B does 2
User A does 3
User B does 4
User A does 5
... 

测试代码随机执行;我无法编写一系列测试,例如:test "user A does 1" do ... end 并期望它们按顺序执行

那么,针对上述情况应该如何编写集成测试呢?

require 'test_helper'

class MyIntegrationTest < ActionController::IntegrationTest

  test "Test interaction between 2 users" do 
    sign_in 'userA@mysite.com'
    assert_response :success

    get '/does/1'
    assert_response :success

    sign_out

    sign_in 'userB@mysite.com'
    assert_response :success

    get '/does/2'
    assert_response :success

    sign_out

    sign_in 'userA@mysite.com'
    assert_response :success

    get '/does/3'
    assert_response :success

    sign_out

    sign_in 'userB@mysite.com'
    # ahhhhhhhhhhhhhhhhhhhhhhhhhhh! .....
  end

请记住,控制器测试可能会在 Rails 5.

中删除
https://github.com/rails/rails/issues/18950#issuecomment-77924771

在 rails 个问题中找到这个:

https://github.com/rails/rails/issues/22742

此处有示例代码URL:

http://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html
http://guides.rubyonrails.org/testing.html#integration-testing-examples

截至 2016 年 1 月 10 日,边缘指南中不存在此内容。

为了来到这里的其他人的利益:出于某种原因,相关的助手似乎没有记录在当前的 Rails 指南中,但我从 https://guides.rubyonrails.org/v4.1/testing.html[=12= 中找到了这个例子]

require 'test_helper'



class UserFlowsTest < ActionDispatch::IntegrationTest
  test "login and browse site" do
    # User david logs in
    david = login(:david)
    # User guest logs in
    guest = login(:guest)
 
    # Both are now available in different sessions
    assert_equal 'Welcome david!', david.flash[:notice]
    assert_equal 'Welcome guest!', guest.flash[:notice]
 
    # User david can browse site
    david.browses_site
    # User guest can browse site as well
    guest.browses_site
 
    # Continue with other assertions
  end
 
  private
 
    module CustomDsl
      def browses_site
        get "/products/all"
        assert_response :success
        assert assigns(:products)
      end
    end
 
    def login(user)
      open_session do |sess|
        sess.extend(CustomDsl)
        u = users(user)
        sess.https!
        sess.post "/login", username: u.username, password: u.password
        assert_equal '/welcome', sess.path
        sess.https!(false)
      end
    end
end

这项技术似乎在 Rails 5.1 应用程序中仍然有效。