Rails Rspec无法访问GET路由问题求助
问题:RSpec测试中调用路由助手失败,视图中正常工作
路由配置
resources :profile do get "remove_photo" get "remove_letter" get "remove_statement" get "remove_resume" get "remove_others" end
控制器对应方法
def remove_photo @cur_user ||= Account.find_by_session_token(session[:session_token]) # for testing @profile = Profile.find_by_account_id @cur_user.id byebug @profile.remove_photo! @profile.save! redirect_to edit_profile_path(@profile) end
视图调用(正常运行)
在Haml视图中使用路由助手完全正常:
= link_to 'delete file', profile_remove_photo_path(@profile)
RSpec测试代码(调用失败)
describe 'test remove photo method' do it 'remove photo successfully' do fake_user = double('User') allow(Account).to receive(:find_by_session_token).and_return(fake_user) fake_profile = double('Profile') allow(Profile).to receive(:find_by_account_id).and_return(fake_profile) allow(fake_user).to receive(:id).and_return(fake_profile) allow(fake_profile).to receive(:remove_photo!) allow(fake_profile).to receive(:save!) get profile_remove_photo_path(1) expect(response).to redirect_to edit_profile_path(1) end end
报错信息
Failures:
ProfileController test remove photo method remove photo successfully
Failure/Error: get profile_remove_photo_path(1)ActionController::UrlGenerationError:
No route matches {:action=>"/profile/1/remove_photo", :controller=>"profile"}./spec/controllers/profile_controller_spec.rb:116:in `block (3 levels) in <top (required)>'
解决思路
- 修正
get方法的调用方式:RSpec控制器测试中,get方法的第一个参数应该是路由对应的action名称,而非完整路径字符串。你当前传递的profile_remove_photo_path(1)会生成完整URL,导致Rails误以为这是action名称,从而报错。正确写法是:get :remove_photo, params: { profile_id: 1 } - 修复double的ID返回值:你设置
fake_user.id返回fake_profile对象,这会让Profile.find_by_account_id接收一个对象而非数值ID,逻辑不合理。应该改成返回数值类型的ID,比如:allow(fake_user).to receive(:id).and_return(1) - 规范测试写法:控制器测试优先使用
action名+参数的方式调用,这是Rails测试的标准实践,可避免直接拼接路径带来的错误。
内容的提问来源于stack exchange,提问作者cs_starter
相关产品推荐
相关产品推荐

