【发布时间】:2018-08-29 22:11:03
【问题描述】:
我需要一些帮助,
当我尝试使用 Rails 中的 ajax 更新模型时出现错误(form_with / remote: true)。我能够很好地处理 Rails 对作为资源的 url 的 XHR 请求(请参阅下面的路线),但是使用自定义 url 我遇到了错误。
控制器:
def criar
@user = current_user
respond_to do |format|
if @user.update_attributes(user_params)
format.js {
flash[:success] = "Success!"
redirect_to root_path
}
else
format.js
end
end
end
rspec(请求):
put user_criar_path(user), xhr: true,
:params => { ... }
查看:
<%= form_with model: @user, url: user_criar_path(@user), method: :put do |f| %>
路线:
namespace :any do
namespace :things do
put '/criar', to: 'user#criar' # problem with XHR
put '/atualizar', to: 'user#atualizar' # problem with XHR
end
end
resources :anything # this one works fine with XHR
正如您在 test.log 中看到的,Processing by UserController#criar as 没有特定的格式(也许这就是问题所在?)。
测试日志:
Processing by UserController#criar as
Parameters: { ... }
错误信息:
Failure/Error:
respond_to do |format|
if @user.update_attributes(user_params)
format.js {
flash[:success] = "Success!"
redirect_to root_path
}
else
format.js
end
ActionController::UnknownFormat:
ActionController::UnknownFormat
另一个请求测试
it "should be redirect to (criar)" do
put user_criar_path(1), xhr: true
expect(response).to redirect_to(new_session_path)
expect(request.flash_hash.alert).to eq "To continue, please, sign in."
end
错误信息
Failure/Error: expect(response).to redirect_to(new_session_path)
Expected response to be a <3XX: redirect>, but was a <401: Unauthorized>
Response body: To continue, please, sign in.
观察:
- 我已经尝试将路由上的 url 更改为:
put '/criar', to: 'user#criar', constraints: -> (req) { req.xhr? } - 正如我之前所说,我正在使用来自
form_with的 XHR 对其他资源执行相同的操作(测试、控制器),并且它们运行良好。这个自定义网址不起作用。 - Rails 5.2 和 Rspec 3.6
- 有任何问题,请在 cmets 上提问
提前致谢!
【问题讨论】:
标签: rspec rspec-rails ruby-on-rails-5.2