无法调用" dummy = create(:user)"创建用户。已经来回走了几个小时。
/home/parreirat/backend-clone/Passworks/spec/models/user_spec.rb:15:in `block (2 levels) in <top (required)>': undefined method `create' for #<Class:0xbcdc1d8> (NoMethodError)"
这是工厂,users.rb:
FactoryGirl.define do
factory :user do
email 'heheheheheheh@gmail.com'
password 'chucknorris'
name 'luis mendes'
end
end
这就是我在user_spec.rb中调用FactoryGirl的方式:
require 'spec_helper'
describe 'User system:' do
context 'registration/login:' do
it 'should have no users registered initially.' do
expect(User.count).to eq(0)
end
it 'should not be logged on initially.' do
expect(@current_user).to eq(nil)
end
dummy = create(:user)
it 'should have a single registered user.' do
expect(User.count).to eq(1)
end
end
end
我按照指示将其添加到spec_helper.rb:
RSpec.configure do |config|
# Include FactoryGirl so we can use 'create' instead of 'FactoryGirl.create'
config.include FactoryGirl::Syntax::Methods
end
答案 0 :(得分:9)
您需要将create
行移到其使用的规范中:
it 'should have a single registered user.' do
dummy = create(:user)
expect(User.count).to eq(1)
end
现在,该行没有上下文(不在规范中而不在before
块中)。这可能是您收到错误的原因。你可能所有设置都正确,但只有一行在错误的地方。
答案 1 :(得分:6)
获得undefined method 'create'
错误的另一个原因可能是您在spec/support/factory_girl.rb
中缺少此配置:
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
我找到了代码here。
答案 2 :(得分:1)
有时候,您只需要在测试文件的顶部require 'rails_helper'
。这解决了我的问题。