使用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
相关产品推荐
相关产品推荐

