Bernardo
Bernardo

Reputation: 529

Testing a create action with rspec and factory is failing

I'm trying to test a post/create controller action in my rails 4 app, but it's failing.

Here is the scaffold generated test:

it "assigns a newly created project as @project" do
  post :create, {:project => valid_attributes}, valid_session
  assigns(:project).should be_a(Project)
  assigns(:project).should 
end

Here is the code after I refactored to use it with FactoryGirl

  it "assigns a newly created project as @project" do
    project = FactoryGirl.create(:post)
    assigns(project).should be_a(Project)
    assigns(project).should be_persisted
  end

So it's failing:

 Failure/Error: assigns(project).should be_a(Project)
   expected nil to be a kind of Project(id: integer, title: string, description: text, created_at: datetime, updated_at: datetime)

I don't know why projectis returning nil in assigns method. I already inspected it to make sure it's returning a proper Project.

Btw, here is my project factory:

factory :project do
  title "MyString"
  description "MyText"
  users {[FactoryGirl.create(:user)]}
end 

Thanks in advance!

Upvotes: 0

Views: 534

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29439

The assigns(project) method call returns the value of the @project instance variable in Rails. Invoking the FactoryGirl method has no effect on this variable, so it evaluates to nil.

Upvotes: 1

Related Questions