0

我正在寻找如何为需要 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
4

2 回答 2

1

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

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 应用程序。

于 2020-06-23T20:47:31.760 回答
0

此网址有示例代码:

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

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

于 2016-01-10T18:58:21.230 回答