FactoryGirl.create始终在spec控制器中失败

时间:2016-05-20 10:11:25

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

所以我有用户模型

我用脚手架

创建它

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

my 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

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'

1 个答案:

答案 0 :(得分:1)

似乎您可以使用控制台创建用户,因为您的开发数据库的表“性别”填充了信息,但您的测试数据库却没有。要了解这是否正在发生,请在测试环境中打开控制台并尝试创建用户。