在尝试提供解决方案后,工厂仍未注册

时间:2015-02-22 05:12:37

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

我第一次尝试编写Rspec测试,我的模型测试工作得很好,但我的控制器测试有问题。这看起来很奇怪。对于我的模型测试,我跟随以下示例:https://gist.github.com/kyletcarlson/6234923

我得到了臭名昭着的Factory not registered:错误。日志如下:

1) ProductsController POST create when given all good parameters
     Failure/Error: post :create, product: attributes_for(valid_product)
     ArgumentError:
       Factory not registered: #<Product:0x007fc47275a330>
     # ./spec/controllers/products_controller_spec.rb:12:in `block (4 levels) in <top (required)>'

我尝试过其他人提供的解决方案,现在我的文件看起来像这样:

Gemfile

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

rails_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
...
RSpec.configure do |config|
  ...
  config.include FactoryGirl::Syntax::Methods
end

/spec/factories/products.rb

FactoryGirl.define do
  factory :product do
    sequence(:name) { |n| "test_name_#{n}" }
    price "1.50"
    description "Test Description"
  end
end

/spec/controllers/products_controller_spec.rb

require 'rails_helper'

describe ProductsController do

  let(:valid_product) { create(:product) }
  let(:invalid_product) { create(:product, name: nil, price: 0, description: test_description) }

  describe "POST create" do

    context 'when given all good parameters' do
      before(:each){
        post :create, product: attributes_for(valid_product)

      }

      it { expect(assigns(:product)).to be_an_instance_of(Product) }
      it { expect(response).to have_http_status 200 }
    end

  end

end

任何帮助将不胜感激。谢谢。 *更新以包括工厂详细信息,这些信息在提出问题之前已经实施。

2 个答案:

答案 0 :(得分:1)

您需要单独指定工厂。使用内容创建spec/factories/products.rb

FactoryGirl.define do
  factory :product do
    name 'My awesome product'
    price  100
    description 'Just a simple awesome product'
    # add there attributes you need 
  end
end 

答案 1 :(得分:1)

在这一行

    post :create, product: attributes_for(valid_product)

您正在调用attributes_for传递valid_product这是Product的实际实例,因此会显示错误消息。

我怀疑你打算写

    post :create, product: attributes_for(:product)