Rails使用Post数据测试XHR

时间:2011-06-18 08:22:21

标签: ruby-on-rails

我只是将我的脚趾浸入Ruby和Rails中,并试图让我的头脑完成整个BDD的事情。我有一个页面,它将一个AJAX POST发送回一个控制器,该控制器有一个名为“sort”的方法,并传递一个像这样的id数组

["song-section-5", "song-section-4", "song-section-6"]

我想为此写一个测试,所以我想出了类似的东西:

test "should sort items" do
  xhr :post, :sort
end

但无法弄清楚如何传递数组。有什么帮助吗?

3 个答案:

答案 0 :(得分:17)

来自Rails source code

def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)

方法的第三个输入是“参数”。这些是发送给你的控制器的参数。

xhr :post, :sort, { :ids => ["song-section-5", "song-section-4", "song-section-6"] }

答案 1 :(得分:10)

对我来说,使用RSpec 3.6和Rails 5.1,之前的回答失败了:

xhr :post, :index

# => NoMethodError: undefined method `xhr' for #<RSpec::ExampleGroups::XController::Index::AJAXRequest:0x007fd9eaa73778>

Rails 5.0 +

请尝试像这样设置xhr: true

post :index, xhr: true

背景

这是ActionController::TestCase中的相关代码。设置xhr标志最终会添加以下标题:

if xhr
  @request.set_header "HTTP_X_REQUESTED_WITH", "XMLHttpRequest"
  @request.fetch_header("HTTP_ACCEPT") do |k|
    @request.set_header k, [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
  end
end

答案 2 :(得分:0)

答案

test "should sort items" do
  post path_to_your_sort_action, params: { ids: ["song-section-5", "song-section-4", "song-section-6"] }, xhr: true, 
end
# using Rails +6 and minitest

我怎么得到答案的?

现代的Rails堆栈更喜欢使用集成测试而不是控制器测试-因此您将使用ActionDispatch::IntegrationTest。如果您要发送发帖请求,只需传递xhr: true

这里是源代码的链接,first指向second,其中包含您要查找的答案。