FactoryGirl未初始化的常量InvalidVoice

时间:2015-08-13 03:08:37

标签: rspec factory-bot

当我遇到此错误时,尝试学习RSpec和FactoryGirl。

Failure/Error: post :create, voice: FactoryGirl.attributes_for(:invalid_voice)
     NameError:
       uninitialized constant InvalidVoice

以下是voice_controller上的简单RSpec

describe '#create' do

        context "with valid inputs" do
            it "creates and increase Voice count by 1" do
                expect{
                    post :create, voice: FactoryGirl.attributes_for(:voice)
                }.to change(Voice, :count).by(1)
            end

            it "redirects to show page" do
                post :create, voice: FactoryGirl.attributes_for(:voice)
                expect(response).to redirect_to Voice.last
            end
        end

        context "with invalid inputs" do
            it "does not increase Voice count" do
                expect{
                    post :create, voice: FactoryGirl.attributes_for(:invalid_voice)
                }.not_to change(Voice, :count)
            end

            it 'renders #new again' do
                post :create, voice: FactoryGirl.attributes_for(:invalid_voice)
                expect(response).to render_template :new
            end
        end
    end

现在,所有上下文"有效输入" 会通过。但是,在 with invalid inputs 上下文中,似乎FG没有注册:invalid_voice是一个有效的输入。

这是我的FG

FactoryGirl.define do
  factory :voice do
    title "MyString"
    opinion "MyText"
  end

  factory :invalid_voice do
    title ""
    opinion ""
  end

end

对于此项目,无效输入仅表示空输入。因此,如果标题或意见为空,则无效,应返回错误/重定向到方法。

我尝试过设置"" nil以及完全删除其中一个属性,但错误仍然存​​在。

我做错了什么?

编辑:

以下情况似乎有效。但有人可以告诉我为什么吗?

factory :invalid_voice, parent: :voice do
    title nil
  end

1 个答案:

答案 0 :(得分:2)

factory :invalid_voice, parent: :voice do
    title nil
end

这是有效的,因为当您将voice定义为invalid_voice的父级时,这意味着invalid_voice继承自voice,并且是voice的一种

如果没有这个,它就无法正常运行并出现此错误:

 NameError:
   uninitialized constant InvalidVoice

因为,您的代码中没有任何名为InvalidVoice的类。但是,您只有Voice类。

您可以使用Inheritence为同一个班级创建多个工厂。而且,您正在为一个班级:voice创建两个工厂:invalid_voiceVoice

您正在执行此操作:factory :invalid_voice, parent: :voice指定Voiceinvalid_voice工厂的关联类,并且因为您已经拥有Voice } class存在于您的代码中。