ruby Rails Rspec无法访问GET路由

zf2sa74q  于 2022-12-12  发布在  Ruby
关注(0)|答案(1)|浏览(83)

我将路径GET“remove_photo”设置为:

resources :profile do
    get "remove_photo"
    get "remove_letter"
    get "remove_statement"
    get "remove_resume"
    get "remove_others"
  end

然后我有我的控制器与方法remove_photo:

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!
    # end
    redirect_to edit_profile_path(@profile)
  end

这在相关的haml视图页面上很好地工作,用profile_remove_photo_path(@profile)调用remove_photo方法

= link_to 'delete file', profile_remove_photo_path(@profile)

但是,当我尝试对remove_photo方法进行rspec测试时,它无法调用profile_remove_photo_path(@profile)方法:
第一个
我真的不明白为什么这个方法在我的haml视图中被成功调用,但是在rspec中却不起作用。非常感谢你的任何想法。
我的尝试如上所示。

xytpbqjk

xytpbqjk1#

终于意识到我的问题了。原来我对rspec的知识还不够。我不应该在这里调用路径profile_remove_photo_path,而应该直接调用方法:remove_photo!!我的rspec现在是这样的。(我根据@max将路由方法从get改为delete

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!)

      # delete profile_remove_photo_path     # rspec should not call the path in rspec!! should call the method!!!
      delete :remove_photo, {:profile_id => 1}          # directly use delete + method, done!!

      # # this line below can recognize path
      # Rails.application.routes.recognize_path profile_remove_photo_path(1)      # Rails recognize this path!
      expect(response).to redirect_to edit_profile_path(fake_profile)

    end
  end

相关问题