使用Rspec2 + Rails3测试控制器的新操作

时间:2013-02-06 11:23:17

标签: ruby-on-rails-3 controller rspec2

我的控制器新操作有以下rspec2测试用例

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

我收到以下错误

  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

当我在==上使用eq时,我收到以下错误

  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>.==.

我在这里做错了什么,提前谢谢

我在

  • Rails3中
  • Rspec2

1 个答案:

答案 0 :(得分:1)

您在访问新操作之前创建了一个新项目,这是不必要的。你的控制器实际上已经为你工作了。您面临的问题是您创建了两个新项目(在您的情况下,您已创建项目:首先是0x007f461c498270,然后是项目:0x007f461c801c90,它们具有相同的属性但是是不同的项目)。该测试应通过:

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