gpt4 book ai didi

ruby-on-rails - 在 RSpec 中销毁的 InvalidAuthenticityToken

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:11 32 4
gpt4 key购买 nike

在 RSpec 上,销毁操作在 ActionController::InvalidAuthenticityToken 中失败。

我认为这不是问题,因为我的 Controller 中的 skip_before_filter :verify_authenticity_token, :only => [:index, :show] 足以解决问题,但它仍然困扰着我这必须发生,而且这似乎是一种糟糕的安全做法。

-

这是可能会失败的 RSpec 测试:

require 'spec_helper'

describe "Products" do
subject { page }
...
describe "Destroy" do
before {
FactoryGirl.create(:product)
visit products_path
}
it "should have a destroy link" do
expect { should have_link('Destroy') }
end
it "link should destroy" do
expect do
click_link('Destroy', match: :first)
end.to change(Product, :count).by(-1)
end
end
end

-

这是 Controller :

class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
skip_before_filter :verify_authenticity_token, :only => [:destroy] #destroy wasn't working without this

def index
@products = Product.all
end

def show
end

def new
@product = Product.new
end

def edit
end

def create
...
end

def update
...
end

def destroy
@product.destroy
flash[:notice] = "Product was successfully destroyed."
redirect_to products_path
end

private
# Use callbacks to share common setup or constraints between actions.
def set_product
@product = Product.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:title, :description, :image_url, :price)
end
end

-

想法?

最佳答案

你是对的,跳过你的真实性 token 检查是个坏主意。至少,确保您只为您的测试环境这样做:

skip_before_filter :verify_authenticity_token, :only => [:destroy] 如果 Rails.env.test?

运行测试时 token 无效的问题可能是在开发环境中运行测试的结果。

确保您的 test_helper.rb 文件正确设置了环境:

Rails.env = 'test'

这比 ENV['RAILS_ENV'] = 'test' 风格的方法更有效。

祝你好运!您是否碰巧找到了其他解决方案?

关于ruby-on-rails - 在 RSpec 中销毁的 InvalidAuthenticityToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23862826/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com