FactoryGirl.create 总是在规范控制器中失败



所以我有用户模型

我用脚手架创建它

测试在模型规范中通过,但在控制器规范中始终失败

我的users_controller_spec

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

我的用户的工厂女孩

FactoryGirl.define do
  factory :user do
    name "MyString"
    sex_id 1 
  end
end

我可以从控制台和用户模型规范创建用户

FactoryGirl.create :user

但是当我尝试从控制器规范创建它时,它总是失败

  1) Api::V1::UsersController GET #show 
 Failure/Error: @user = FactoryGirl.create :user
 ActiveRecord::InvalidForeignKey:
   PG::ForeignKeyViolation: ERROR:  insert or update on table "users" violates foreign key constraint "fk_rails_12f007df76"
   DETAIL:  Key (sex_id)=(1) is not present in table "sexs".
   : INSERT INTO "users"
  # ------------------
 # --- Caused by: ---
 # PG::ForeignKeyViolation:
 #   ERROR:  insert or update on table "users" violates foreign key constraint "fk_rails_12f007df76"
 #   DETAIL:  Key (sex_id)=(1) is not present in table "sexs".
 #   /home/user/.rvm/gems/ruby-2.1.8/gems/factory_girl-4.7.0/lib/factory_girl/configuration.rb:18:in `block in initialize'

似乎您可以使用控制台创建用户,因为您的开发数据库包含填充了信息的表"sexs",但您的测试数据库没有。要确定是否正在发生这种情况,请在测试环境中打开控制台并尝试创建用户。

最新更新