Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec + FactoryGirl and controller specs

I'm trying to add FactoryGirl support the default scaffolded specs in my controllers and I can't seem to find the correct syntax.

Here's an example test:

describe "POST create" do
    describe "with valid params" do
   it "creates a new Course" do
        expect {
          post :create, {:course => valid_attributes}, valid_session
        }.to change(Course, :count).by(1)
      end
do

Which I replace by:

describe "POST create" do
    describe "with valid params" do
      it "creates a new Course" do
        expect {
          post :create, course: FactoryGirl.build(:course)
        }.to change(Course, :count).by(1)
      end
do

spec/factories/courses.rb

FactoryGirl.define do
  factory :course do
    association :provider
    name "Course name"
    description "course description"
  end
end

app/models/course.rb

class Course < ActiveRecord::Base
  validates :name, :presence => true
  validates :description, :presence => true
  validates :provider_id, :presence => true
  has_many :terms
  belongs_to :provider
end

app/controllers/courses_controller.rb

  # POST /courses
  # POST /courses.json

  def create
    @course = Course.new(course_params)

    respond_to do |format|
      if @course.save
        format.html { redirect_to @course, notice: 'Course was successfully created.' }
        format.json { render action: 'show', status: :created, location: @course }
      else
        format.html { render action: 'new' }
        format.json { render json: @course.errors, status: :unprocessable_entity }
      end
    end
  end

It usually fails with: "ActionController::ParameterMissing: param not found: course" does anyone have any idea?

Thanks! Francis

like image 465
Francis Ouellet Avatar asked Dec 20 '22 21:12

Francis Ouellet


1 Answers

Try:

    describe "POST create" do
        describe "with valid params" do
          it "creates a new Course" do
            expect {
              post :create, course: FactoryGirl.attributes_for(:course, provider_id: 1)
            }.to change(Course, :count).by(1)
          end
        end
     end

Factory Girl uses attributes_for option to generate a hash of values as opposed to a Ruby object.

like image 153
AbM Avatar answered Dec 30 '22 07:12

AbM