Search code examples
ruby-on-railsfactory-botrspec-rails

Factory still not registered after trying solutions provided


I am trying to write an Rspec test for the first time, my model test worked out fine, but I have problems with my controller test. Which seems weird. For my model test, I'm following the example from: https://gist.github.com/kyletcarlson/6234923

I am given the infamous Factory not registered: error. The log is below:

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)>'

I have tried solutions given by others and now my files look like this:

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

Any help will be appreciated. Thanks. *Updated to include factories details, that was already implemented before question was posed.


Solution

  • On this line

        post :create, product: attributes_for(valid_product)
    

    You are calling attributes_for passing valid_product which is an actual instance of Product, hence the error message.

    I suspect you intended to write

        post :create, product: attributes_for(:product)