1

我是 factory_girl 菜鸟,无法确定为什么工厂没有“注册”。不知道在哪里注册。

Gemfile 的相关部分:

...
group :development, :test do
  gem 'rspec-rails'
  gem 'factory_girl_rails'
end

group :test do
  gem 'faker'
  gem 'capybara'
  gem 'guard-rspec'
  gem 'launchy'
end
...

config/application.rb 的相关部分:

...
module Appname
  class Application < Rails::Application
    ...
    config.generators do |g|
      g.test_framework :rspec,
        :fixtures => true,
        :view_specs => false,
        :helper_specs => false,
        :routing_specs => true,
        :controller_specs => true,
        :request_specs => true
      g.fixture_replacement :factory_girl, :dir => "spec/factories"
    end
    ...
  end
end

spec/models/user_spec.rb 的相关部分:

require 'spec_helper'

describe User do
  it "has a valid factory" do
    FactoryGirl.create(:user).should be_valid
  end
  ...
end

$rspec spec/models/user_spec.rb 的结果:

Failures:

  1) User has a valid factory
     Failure/Error: FactoryGirl.create(:user).should be_valid
     ArgumentError:
       Factory not registered: user

更新:

规格/工厂/users.rb:

require 'faker'

FactoryGirl.define do
  factory :contact do |f|
    f.first_name { Faker::Name.first_name }
    f.last_name { Faker::Name.last_name }
    f.email { Faker::Internet.email }
    f.password { Faker::Name.last_name }
    f.password_confirmation { Faker::Name.last_name }
  end
end

谢谢你的帮助。

4

2 回答 2

2

从评论线程:您可能希望将factory :contact您的工厂更改为factory :user

FactoryGirl.define do
  factory :user do |f|
    ...
  end
end
于 2012-10-27T00:26:58.020 回答
1

试试这个,在你的app/spec/factories/文件夹中创建user.rb并写入

require 'factory_girl'

FactoryGirl.define do
  factory :user do
    lname "test12"
    fname "test12"
    ... # whatever
  end
end

在你的user_spec.rb

describe User do
  before { @user = FactoryGirl.create(:user, :fname => "abc", :lname => "fname") }
  subject { @user }
  it { should respond_to(:fname) }
  it { should respond_to(:lname)}
  it { should be_valid }
end
于 2012-10-26T06:47:20.280 回答