Rspec控制器分配不能按预期工作

时间:2018-05-13 10:45:34

标签: ruby-on-rails testing rspec controller

在这个项目中我使用:

gem 'rails', '~> 5.1.1' 
gem 'mongoid', '~> 6.1.0' 
gem 'rspec-rails', '~> 3.7'

我有模特书:

class Book
  include Mongoid::Document
  field :name, type: String
  field :author, type: String
  field :description, type: String
  field :status, type: String
  field :image, type: String

  has_many :histories, dependent: :destroy
  has_many :likes, dependent: :destroy
  has_many :comments, dependent: :destroy

  validates :name, :author, :description, :status, :image, presence: true

  def ordered_histories
    histories.order(taken_in: :desc)
  end

  def book_rating
    rating_array = likes.map { |like| like.rate.to_i }
    return 0 if rating_array.empty?
    (rating_array.sum / rating_array.size).round
  end
end

在Books控制器中,我只有索引和显示操作。 以下是与Books控制器的索引操作相关的代码:

class BooksController < ApplicationController
  before_action :set_top_books, only: :index

  # GET /books
  # GET /books.json
  def index
    @books = Kaminari.paginate_array(Book.all).page(params[:page])
  end

  private

  def set_top_books
    @top_books = Book.all.order_by(likes_count: :desc, histories_count: :desc).limit(5)
  end
end

我有工厂书。这是代码:

FactoryBot.define do
  factory :book do
    name { Faker::Book.title }
    author { Faker::Book.author }
    description { Faker::Lorem.paragraph }
    image { Faker::Lorem.sentence }
    status { 'In' }
  end
end

这是我对控制器书籍行动指数的测试

require 'rails_helper'

RSpec.describe BooksController, type: :controller do
  before(:each) do
    @user = create(:user)
    sign_in @user
  end

  describe 'GET #index' do
    it 'assigns @books' do
      book = create(:book)
      get :index
      expect(assigns(:books)).to eq([book])
    end

    it 'render index template' do
      get :index
      expect(response).to render_template('index')
      expect(response).to have_http_status(200)
    end
  end
end

我在这一行中遇到了问题 expect(assigns(:books)).to eq([book])。在这个地方测试失败。我不明白为什么,因为我的开发环境代码按预期工作。我还在文档中通过示例进行了测试。这是测试的控制台输出:

Failures:

  1) BooksController GET #index assigns @books
     Failure/Error: expect(assigns(:books)).to eq([book])

       expected: [#<Book _id: 5af815723a4f8d22e7f3daed, name: "The Lathe of Heaven", author: "Edwin Runolfsdottir", de...t aut.", status: "In", image: "Nulla culpa sint perspiciatis nihil saepe perferendis quidem sint.">]
            got: [#<Book _id: 5af718cc3a4f8d176e551d86, name: "Precious Bane", author: "Aiden Dicki", description: "Op...luptatibus et sint soluta debitis saepe.", status: "In", image: "Aut et expedita placeat ut quos.">]

       (compared using ==)

       Diff:
       @@ -1,2 +1,6 @@
       -[#<Book _id: 5af815723a4f8d22e7f3daed, name: "The Lathe of Heaven", author: "Edwin Runolfsdottir", description: "Et dolorem tenetur et dolore. Sit et magni et ut quos quia. Ab expedita tenetur laborum cumque repellendus magnam. Perferendis saepe id cumque qui numquam. Non maxime et aut.", status: "In", image: "Nulla culpa sint perspiciatis nihil saepe perferendis quidem sint.">]
       +[#<Book _id: 5af718cc3a4f8d176e551d86, name: "Precious Bane", author: "Aiden Dicki", description: "Optio quisquam assumenda quaerat non et blanditiis ea. Fugit necessitatibus ipsum cupiditate. Suscipit explicabo vitae tempora illum omnis. Ipsum quam dolore. Rerum possimus ut vero non reprehenderit laboriosam.", status: "In", image: "Est sed autem molestiae earum.">,
       + #<Book _id: 5af718cc3a4f8d176e551d88, name: "Terrible Swift Sword", author: "Rey Beer", description: "Consequatur eligendi eaque aut quisquam voluptatum. Labore ad dolore expedita reiciendis repellat est. Error dolor et doloremque. Velit in qui fugit recusandae quia. Atque non ut accusantium consequatur similique.", status: "In", image: "Illum mollitia sed facere dolor quisquam nisi facilis.">,
       + #<Book _id: 5af718cc3a4f8d176e551d8a, name: "Bury My Heart at Wounded Knee", author: "Viva Leuschke PhD", description: "Voluptatum voluptatem laudantium possimus debitis suscipit velit. Eius assumenda dolorem. Praesentium officia provident. Officia soluta adipisci exercitationem aut at totam eveniet.", status: "In", image: "Ipsum qui nemo enim quo molestiae rerum fugit unde.">,
       + #<Book _id: 5af718cc3a4f8d176e551d8d, name: "Down to a Sunless Sea", author: "Tristian Breitenberg", description: "Ullam sunt repudiandae commodi aliquid repellendus est. Aut reprehenderit in magni saepe quis. Commodi incidunt sit. In repellat beatae aut et esse quae. Veniam nemo natus.", status: "Out", image: "Aut aut commodi quam et quis dolore non voluptates.">,
       + #<Book _id: 5af718cd3a4f8d176e551d90, name: "The Wives of Bath", author: "Devonte Mraz", description: "Similique enim neque et autem libero. Dolorem alias aut est veniam aperiam ea repellat. Consectetur iure quae nihil eos quo et. Voluptatibus et sint soluta debitis saepe.", status: "In", image: "Aut et expedita placeat ut quos.">]

此外,我尝试将页面作为参数传递,如下所示:

get(:index, params: { page: 1 })

但它没有帮助。 请帮我解决这个问题,因为我所有的其他测试都运行正常。如果您需要更多信息,请告诉我。我可以提供GitHub网址。提前谢谢。

1 个答案:

答案 0 :(得分:1)

这是一个与数据库相关的问题并不干净。作为快速修复尝试添加:

http://.../test/

创建图书之前。在您回复时,数据库清理程序的配置是一个强大的解决方案:

Book.destroy_all