当我遇到这个错误时,试图学习RSpec和FactoryGirl。
Failure/Error: post :create, voice: FactoryGirl.attributes_for(:invalid_voice)
NameError:
uninitialized constant InvalidVoice下面是一个简单的RSpec在voice_controller上
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现在,所有“具有有效输入”的上下文都将通过。然而,在输入无效的中,上下文似乎没有将:invalid_voice注册为有效输入。
这是我的FG
FactoryGirl.define do
factory :voice do
title "MyString"
opinion "MyText"
end
factory :invalid_voice do
title ""
opinion ""
end
end对于这个项目,无效的输入仅仅意味着空输入。因此,如果标题或意见为空,则无效,应将错误/重定向返回到新方法。
我尝试将"“设置为”0“,并完全删除其中一个属性,但错误仍然存在。
我做错了什么?
编辑:
看来,下面的工作。但谁能告诉我原因吗?
factory :invalid_voice, parent: :voice do
title nil
end发布于 2015-08-13 03:43:20
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_voice创建两个工厂Voice。
这就是您要做的:factory :invalid_voice, parent: :voice来指定Voice是invalid_voice工厂的关联类,并且在代码中已经有一个Voice类。
https://stackoverflow.com/questions/31978861
复制相似问题