我正在測試一個控制器,該控制器的動作呈現視圖的格式爲.js.erb。 對這些行動的測試提高了以下錯誤:渲染JS視圖時提升InvalidCrossOriginRequest的Ruby on Rails測試
Minitest::UnexpectedError: ActionController::InvalidCrossOriginRequest: Security warning: an embedded tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.
的防僞保護導致這個錯誤,因爲當我把一個異常有關這些操作的好,但我不希望將其禁用。
這裏是我的控制器:
class TasksController < ApplicationController
def new
# TODO add blah later
@task = Task.new
render 'tasks/show_form.js.erb'
end
def create
# FIXME there is bug here
@task = Task.new(task_params)
@task.user = current_user
authorize! :create, @task
save_task
end
def edit
@task = Task.find(params[:id])
authorize! :edit, @task
render 'tasks/show_form.js.erb'
end
def update
@task = Task.find(params[:id])
@task.assign_attributes(task_params)
authorize! :update, @task
save_task
end
def destroy
@task = Task.find(params[:id])
authorize! :destroy, @task
@task.destroy
@tasks = Task.accessible_by(current_ability)
end
private
def save_task
if @task.save
@tasks = Task.accessible_by(current_ability)
render 'tasks/hide_form.js.erb'
else
render 'tasks/show_form.js.erb'
end
end
def task_params
params.require(:task).permit(:title, :note, :completed)
end
end
這裏是我的這個控制器測試:
require 'test_helper'
class TasksControllerTest < ActionDispatch::IntegrationTest
#include Devise::Test::ControllerHelpers
def setup
@task = tasks(:one)
@password = "password"
@confirmed_user = User.create(email: "#{rand(50000)}@example.com",
password: @password,
confirmed_at: "2020-02-01 11:35:56")
@unconfirmed_user = User.create(email: "#{rand(50000)}@example.com",
password: @password,
confirmed_at: "")
sign_in(user: @confirmed_user, password: @password)
end
test "should get new" do
get new_task_url
assert_response :success
end
test "should create task" do
assert_difference('Task.count') do
post tasks_url, params: {task: {title: 'Dont fail test !'}}
end
assert_redirected_to task_url(Task.last)
end
test "should get edit" do
get edit_task_url(@task)
assert_response :success
end
test "should update task" do
patch task_url(@task), params: {task: {title: 'updated'}}
assert_redirected_to task_url(@task)
article.reload
assert_equal "updated", article.title
end
test "should destroy task" do
assert_difference('Task.count', -1) do
delete task_url(@task)
end
assert_redirected_to tasks_url
end
end
做任何你對如何糾正這個錯誤的想法?
預先感謝您
您是否想故意在您的應用中執行cors,或意外發生?如果你想做cors,那麼使用[rack-cors](https://github.com/cyu/rack-cors)怎麼樣? – YTorii
我會說意外的,因爲我只使用自己的資源。感謝您的幫助,我找到了解決方案:) –