简体   繁体   中英

Visit path passing id with Capybara on Rails

I am working on a Rails project, where I'm using Rspec to unit tests with Capybara to visit the pages. I have this real url: http://localhost:3000/teacher/courses/2778/audience where 2778 is the course id and this page show the student (audience) in that course of the teacher logged in.

My routes.rb for this resource looks like this:

...
namespace :teacher do
  ...
  resources :courses, except: [:delete] do
    member do
      ...
      get :audience
      ...
    end
  end
end

And in my unit test I'm already logged in as a particular teacher and I have a variable @course which represents the related course, now, I need to go directly to that url or path. I've already attempted:

visit '/teacher/courses/@course.id/audience'
visit '/teacher/courses/' + @course.id + '/audience'
visit '/teacher/courses/#{@course.id}/audience'

but nothing of this has worked.

How can I visit this path?

String interpolation requires double quotes " try:

visit "/teacher/courses/#{@course.id}/audience" 

This will become visit "/teacher/courses/12/audience" assuming @course.id is 12.

Right now these are the issues.

First example: visit '/teacher/courses/@course.id/audience' is an explicit string so it is trying to visit '/teacher/courses/@course.id/audience' as the true URL.

Second example: visit '/teacher/courses/' + @course.id + '/audience' will raise TypeError: no implicit conversion of Fixnum into String because id is a Fixnum and cannot be implicitly converted.(could be solved by @course.id.to_s but that looks dirty)

Third example: visit '/teacher/courses/#{@course.id}/audience' is also an explicit string because of the lack of double quotes and will act the same way as the first except it is trying to use /teacher/courses/#{@course.id}/audience as the URL inclusive of the curly braces.

Also as @MusannifZahir pointed out you should make sure this course exists in your test db. My answer assumes this is not the actual issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM