LoginSignup
1
0

More than 3 years have passed since last update.

RSpecエラー Failure/Error: expect(show_link[:href]).to eq book_path(book) expected: "/books/1" got: "/books/6"

Last updated at Posted at 2021-04-16

RSpecでエラー出た

以下Error発生

terminal
Failures:

  1) 投稿のテスト 一覧画面のテスト 一覧の表示とリンクの確認 bookのタイトルと感想を表示し、詳細・編集・削除のリンクが表示されているか
     Failure/Error: expect(show_link[:href]).to eq book_path(book)

       expected: "/books/1"
            got: "/books/6"

       (compared using ==)
     # ./spec/system/books_spec.rb:40:in `block (5 levels) in <main>'
     # ./spec/system/books_spec.rb:33:in `each_with_index'
     # ./spec/system/books_spec.rb:33:in `block (4 levels) in <main>'

Finished in 1.78 seconds (files took 1.5 seconds to load)
28 examples, 1 failure

Failed examples:

rspec ./spec/system/books_spec.rb:28 # 投稿のテスト 一覧画面のテスト 一覧の表示とリンクの確認 bookのタイトルと感想を表示し、詳細・編集・削除のリンクが表示されているか

何度調べても、出てこなかったので備忘録として。
このエラー解決した時には、「なんやねん」って感じの単純なミスでした。

index.html.erb

index.html.erb
----------省略------------
<tbody>
  <% @books.each do |b| %>
    <tr>
      <td><%= b.title %></td>
      <td><%= b.body %></td>
      <td><%= link_to 'Show', book_path(b), class:'jump' %></td>
      <td><%= link_to 'Edit', edit_book_path(b), class:'jump' %></td>
      <td><%= link_to 'Destroy',
                       book_path(b),
                       method: :delete,
                       data: { confirm: 'Are you sure?' },
                       class:'jump' %></td>
    </tr>
  <% end %>
</tbody>
----------省略------------

見た感じ、リンクの書き方は合ってる。

terminalでrails routesでpathを確認してください。
私は、routes.rbで以下記述です

routes.rb
Rails.application.routes.draw do
  root to: 'home#top'

  resources :books 
end

解決法

books_controller.rb
class BooksController < ApplicationController
  def index
    @books = Book.all.order(created_at: 'desc') < 削除 >
    @books = Book.all < 追記 >
    @book = Book.new
  end

< 省略 >

end

以上のように、@books = Book.all.order(created_at: 'desc')としていると、降順になるのでidの順番が逆になる。

学んだこと

expected: "/books/1"
got: "/books/6"

のように、params[:id]の数字の部分がexpectedgotで「違うで」とError表示されたら、コントローラーを確認する


間違っていたら、教えてください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0