工厂女孩没有正确制作属性

时间:2016-07-24 01:43:45

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

我在名为Form的模型上使用Rspec编写controller_spec_test。我使用FactoryGirl生成模型。当我在form_controller_spec中运行单独的测试时,它们都会通过。但是,当我运行整个文件时,我发现所有测试都失败了,错误消息为ActiveRecord::RecordInvalid: Validation failed: Form type can't be blank

这是我的forms.rb Factorygirl文件, FactoryGirl.define做

  factory :form do
    association :user
        sequence :form_type do |n|
            Form.form_types.values[n]
        end

  end
end

这是我的form.rb模型文件:

class Form < ActiveRecord::Base
  belongs_to :user, required: true

    enum form_types: { :a => "Form A", :b => "Form B", :c => "Form C", :d => "Form D"}

  validates :form_type, presence: true
  validates :form_type, uniqueness: {scope: :user_id}

end

这是我的forms_controller_spec.rb文件:

require 'rails_helper'

RSpec.describe FormsController, type: :controller do

  login_user

    let(:form) {
        FactoryGirl.create(:form, user: @current_user)
    }

    let(:forms) {
        FactoryGirl.create_list(:form , 3, user: @current_user)

    }

    let(:form_attributes) {
        FactoryGirl.attributes_for(:form, user: @current_user)
    }

    describe "GET #index" do
        before do
            @forms = forms
        end

        it "loads all of the forms into @forms" do
            get :index
            expect(assigns(:forms)).to match_array(@forms)
        end
    end

end

我没有得到单个测试正在通过,但是当我运行整个文件时测试失败了。我也不知道为什么form_type是空的。

1 个答案:

答案 0 :(得分:0)

您的:form_attributes方法缺少适当的值:form_type

let(:form_attributes) {
    FactoryGirl.attributes_for(:form, "Form C", user: @current_user)
}

虽然您似乎无法决定是否需要字符串或整数,但在上面let(:forms)的调用中,您已经传入整数3。&#3 39;可能需要以某种方式修复的不一致。