水豚重定向到 JSON 响应

Capybara redirecting to JSON response

我的 rails 应用程序中有一个表单可以将数据远程发送到控制器操作。然后 JavaScript 等待成功的 AJAX 响应,然后更新页面的各个部分。

当使用 Turnip、Rspec 和 Capybara 进行测试时,current_page 被重定向到 JSON 响应,而不是像我预期的那样停留在页面上。

下面是部分代码:

被击中的控制器动作

def update
  @conversation.update(conversation_params)
  @conversation.save
  render json: @conversation, serializer: ConversationSerializer
end

形式

= simple_form_for(convo, remote: true, method: :json) do |f|
  - f.fields_for :messages, Message.new(conversation: f.object) do |msg|
    = msg.input :text, label: 'Message'
    = msg.submit 'Post Message', id: 'message-submit'

侦听成功的 Coffeescript

$(document).on 'ajax:success', 'form[data-remote]', (xhr, data, status) ->
  new_message_id = data.conversation.conversation_messages.pop().id

  $.get '/conversation_messages/'+new_message_id+'/partial', (data) ->
    $('#conversation .message').last().after(data)

$(document).on 'ajax:success', 'a[data-remote]', (xhr, data, status) ->
  location.reload()

$(document).on 'ajax:success', 'form[data-remote]', (xhr, data, status) ->
  location.reload()

显示错误内容的测试

step 'I say :message' do |message|
  fill_in 'Message', with: message
  click_on 'Post Message'
end

step 'I see the conversation message :message from :username' do |message, username|
  expect(page).to have_selector('.conversation-message-sender', text: username)
  expect(page).to have_selector('.conversation-message-text', text: message)
end

您需要使用支持 JavaScript 的驱动程序才能使 ajax 提交工作 - 请参阅 https://github.com/jnicklas/capybara#drivers