hi all,
how do you use factory girl in controller specs of a nested
resource?
I am running rails 3.2.0.
I have the following nested resource controller which is failing.
I know very well that the nested resource's object needs the id of the
parent object to search for. The factory girl object for the parent
object, @category is valid as i can print its id out but when the
nested resource's controller tries to use the category id value from
the parameters (as assigned to in valid_attributes) ,it fails saying
that the category id is not there.
I'm puzzled.
Consider the controller spec below:
-------------- extract of spec/controllers/
sub_categories_controller_spec.rb - start ----------
describe SubCategoriesController do
# This should return the minimal set of attributes required to
create a valid
# SubCategory. As you add validations to SubCategory, be sure to
# update the return value of this method accordingly.
@category = FactoryGirl.create(:category_intakes)
def valid_attributes
{
:name => 'turbos',
:description => 'Mr Wankel should be proud',
:category => @
category.id, # or even, "@category.id.to_s,"
:created_by => 1,
:updated_by => 1
}
end
login_admin_user
describe "GET index" do
it "assigns all sub_categories as @sub_categories" do
sub_category = SubCategory.create! valid_attributes
get :index
assigns(:sub_categories).should eq([sub_category])
end
end
-------------- extract of spec/controllers/
sub_categories_controller_spec.rb - end ----------
-------- extract of controllers/sub_categories_controller.rb --- start
--------
class SubCategoriesController < ApplicationController
before_filter :authenticate_user!, :except => [:index, :show]
before_filter :find_category
# GET /sub_categories
# GET /sub_categories.json
def index
@sub_categories = @category.sub_categories
puts " In the index of sub cats now ..." +
@sub_categories.inspect
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @sub_categories }
end
end
private
def find_category
@category = Category.find(params[:category_id])
end
end
-------- extract of controllers/sub_categories_controller.rb --- end
--------
The error message I see with the spec's failure reads, "
1) SubCategoriesController GET new assigns a new sub_category as
@sub_category
Failure/Error: get :new
ActiveRecord::RecordNotFound:
Couldn't find Category without an ID
# /Users/anexiole/projects/try_rails/app/controllers/
sub_categories_controller.rb:102:in `find_category'
# ./sub_categories_controller_spec.rb:59:in `block (3 levels) in
<top (required)>'
"