You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用rspec-rails 6编写请求测试时遇ActionDispatch::TestResponse无to方法错误

解决Rails 7 + RSpec-Rails 6中请求测试的undefined method 'to'错误

你的错误根源是RSpec断言语法使用错误:Ruby会把expect response.to render_template :show解析为尝试调用response.to(render_template :show),但ActionDispatch::TestResponse对象并没有to方法,因此抛出undefined method 'to'异常。

RSpec 3+及RSpec-Rails 6的标准断言语法要求将被校验的对象放在expect()的括号内,再链式调用.to匹配器。修正后的代码如下:

require 'rails_helper'

RSpec.describe 'GuestTokens', type: :request do
  describe 'GET /guest_tokens/:id' do
    context 'with a JSON format' do
      let(:guest_token) { FactoryBot.create(:guest_token) }

      it 'should return a JSON object of the guest token' do
        get "/guest_tokens/#{guest_token.id}.json"

        expect(response).to render_template :show
      end
    end
  end
end

只需给response加上括号,让Ruby正确识别expect(response)作为断言主体,后续的.to render_template :show就能正常调用RSpec的匹配器逻辑。

内容的提问来源于stack exchange,提问作者Michael Pell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:50:17