测试 rspec 和 factorygirl 不工作

Test with rspec and factorygirl not working

我正在关注 this tutorial 以获得 rails API,但它有点过时并且某些功能似乎不适用于新版本的 rails .我在用户控制器规格方面遇到困难:

user_controller_spec.rb

require 'rails_helper'
RSpec.describe Api::V1::UsersController, type: :controller do
  describe "GET #show" do
    before(:each) do
      @user = FactoryGirl.create :user
      get :show, params: {id: @user.id}
    end

    it "returns the information about a reporter on a hash" do
      user_response = JSON.parse(response.body, symbolize_name: true)
      expect(user_response[:email]).to eql @user.email
    end

    it { expect(response).to have_http_status(200) }
  end
end

user_controller.rb

class Api::V1::UsersController < ApplicationController
  def show
    render json: User.find(params[:id])
  end
end

user.rb工厂

FactoryGirl.define do
  factory :user do
    email { FFaker::Internet.email }
    password "12345678"
    password_confirmation "12345678"
  end
end

但是,这不起作用,电子邮件似乎不匹配。有什么想法可能是错误的吗?

失败:

  1) Api::V1::UsersController GET #show returns the information about a reporter on a hash
     Failure/Error: expect(user_response[:email]).to eql @user.email

       expected: "mitzie_nikolaus@rice.com"
            got: nil

       (compared using eql?)
     # ./spec/controllers/api/v1/users_controller_spec.rb:12:in `block (3 levels) in <top (required)>'

代码是正确的,但是您在使用 JSON.parsesymbolize_names 选项时输入错误。

我假设,因为你没有复制粘贴示例,而是自己输入,这很好,因为它更利于学习。

要修复测试,只需更正此行(将 symbolize_name 更改为 symbolize_names):

user_response = JSON.parse(response.body, symbolize_names: true)