Iván Cortés
Iván Cortés

Reputation: 652

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?

Upvotes: 0

Views: 5868

Answers (1)

engineersmnky
engineersmnky

Reputation: 29598

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.

Upvotes: 5

Related Questions