Home > Enterprise >  Rails RSpec: Test the "show" page
Rails RSpec: Test the "show" page

Time:06-21

I am struggling with a very simple issue - as I am trying to learn RSpec:

I want to ensure that when I go to the "show" page of my model and pass in the ID of a given record, the response is a success. I am trying to adopt a bit of TDD, so haven't even customized the view (although there is an empty show.html.erb available).

Here's the test:

require 'rails_helper'

RSpec.describe Book, type: :request do

  describe 'GET /show' do
    it 'returns http success' do
      book = Book.create(title: 'The Hobbit', year: 1937)
      get :show, params: { id: book.to_param }
      expect(response).to be_success
    end
  end

end

I don't get how I need to write this. I get an error like this:

 Failure/Error: get :show, params: { id: book.to_param }
 
 URI::InvalidURIError:
   bad URI(is not URI?): "http://www.example.com:80show"

Any hints?

CodePudding user response:

Replace your test with this and run it:

require "rails_helper"

RSpec.feature "Users can view books >" do
  scenario "by clicking the Show link" do
    book = Book.create(title: "The Hobbit", year: 1937)
    visit "/"
    click_link "Show"
    expect(page).to have_content "The Hobbit"
  end
end

CodePudding user response:

I found out that I needed to describe the spec differently. This is what worked - found here.

require 'rails_helper'

RSpec.describe BooksController, type: :controller do

  describe 'GET /show' do
    it 'returns http success' do
      book = Book.create(title: 'The Hobbit', year: 1937)
      get :show, params: { id: book.to_param }
      expect(response).to have_http_status(200)
    end
  end

end
  • Related