Search code examples
ruby-on-rails-3controllerrspec2

Testing controller new action with Rspec2 + Rails3


I have the following rspec2 test case for my controller new action:

describe "GET #new" do
  it "should assign new project to @project" do
    project = Project.new
    get :new
    assigns(:project).should eq(project)
  end
end

and I'm getting the following error:

  1) ProjectsController GET #new should assign new project to @project
     Failure/Error: assigns(:project).should eq(project)
       
       expected: #<Project id: nil, name: nil, company_id: nil, created_at: nil, updated_at: nil>
            got: #<Project id: nil, name: nil, company_id: nil, created_at: nil, updated_at: nil>
       
       (compared using ==)
       
       Diff:#<Project:0x007f461c498270>.==(#<Project:0x007f461c801c90>) returned false even though the diff between #<Project:0x007f461c498270> and #<Project:0x007f461c801c90> is empty. Check the implementation of #<Project:0x007f461c498270>.==.
     # ./spec/controllers/projects_controller_spec.rb:19:in `block (3 levels) in <top (required)>'

Finished in 1.21 seconds
13 examples, 1 failure, 10 pending

Failed examples:

rspec ./spec/controllers/projects_controller_spec.rb:16 # ProjectsController GET #new should assign new project to @project

and when I use == instead on eq, I'm getting the following error

  1) ProjectsController GET #new should assign new project to @project
     Failure/Error: assigns(:project).should == project
       expected: #<Project id: nil, name: nil, company_id: nil, created_at: nil, updated_at: nil>
            got: #<Project id: nil, name: nil, company_id: nil, created_at: nil, updated_at: nil> (using ==)
       Diff:#<Project:0x007f461c4f5420>.==(#<Project:0x007f461c63b280>) returned false even though the diff between #<Project:0x007f461c4f5420> and #<Project:0x007f461c63b280> is empty. Check the implementation of #<Project:0x007f461c4f5420>.==.

What am I doing wrong here?

I'm on

  • Rails3
  • Rspec2

Solution

  • You are creating a new project before accessing the new action, this is unnecessary. Your controller actually does that work for you already. The problem you are facing is that you have two new projects created (in your case you have created Project:0x007f461c498270 first and then Project:0x007f461c801c90, they have the same attributes but are different projects). This test should pass:

    describe "GET #new" do
      it "assigns a new Project to @project" do
        get :new
        assigns(:project).should be_a_new(Project)
      end
    end