测试与rspec和factorygirl不工作

时间:2017-07-22 12:53:51

标签: ruby-on-rails ruby rspec factory-bot

我跟随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 factory

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)>'

1 个答案:

答案 0 :(得分:0)

代码是正确的,但您在使用symbolize_names的{​​{1}}选项时输错了。

我认为,因为你没有复制粘贴示例,而是自己输入,这很好,因为它更适合学习。

要修正测试,只需更正此行(将JSON.parse更改为symbolize_name):

symbolize_names