【问题标题】:Testing if a controller renders a JS Template测试控制器是否呈现 JS 模板
【发布时间】:2013-07-25 23:05:55
【问题描述】:

我有这个控制器:

class UsersController < ApplicationController
  def enable_password_change
    respond_to do |format|
      format.js {
        render :layout => false
      }
    end
  end
end

还有以下测试:

test "should render js to show the change password form" do
  sign_in_user
  request_javascript
  get :enable_password_change
  assert_template :enable_password_change
  assert_response :ok
end

以及设置请求头的辅助方法:

def request_javascript
  @request.headers["Accepts"] = "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
end

但是我的测试报告:

Finished tests in 0.942294s, 7.4287 tests/s, 15.9186 assertions/s.

1) Error:
UsersControllerTest#test_should_render_js_to_show_the_change_password_for:
ActionController::UnknownFormat: ActionController::UnknownFormat
app/controllers/users_controller.rb:9:in `enable_password_change'
test/controllers/users_controller_test.rb:14:in `block in <class:UsersControllerTest>'

7 tests, 15 assertions, 0 failures, 1 errors, 0 skips

我在这里做错了什么?

【问题讨论】:

    标签: ruby-on-rails testing ruby-on-rails-4


    【解决方案1】:

    我找到了 xml_http_request 或别名 xhr

    test "should render js to show the change password form" do
       sign_in_user
    
       xhr :get, :enable_password_change
    
       assert_template :enable_password_change
       assert_response :ok
       assert assigns(:merchant_user)
    end
    

    【讨论】:

      【解决方案2】:

      在TestCase 的一个实例中,#get 调用#process 调用@request.recycle!它将 @request.headers 设置为空哈希。要测试 js 响应,我认为您必须让测试使用 Selenium 或类似的东西启动浏览器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-03
        • 1970-01-01
        • 2021-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多