使用rspec测试rails控制器:值相同,但对象ID不同

时间:2012-11-29 07:36:28

标签: ruby-on-rails-3 rspec

我尝试用这样的rspec测试rails控制器:

require 'spec_helper'

describe NewsController do  
  describe "GET 'edit'" do
    before(:each) do
      @news_1 = FactoryGirl.create(:news_1)
      get :edit, { :id => @news_1.id }
    end
    it { response.should be_success }
    it { assigns(:news).should eq(@news_1) }
    it { response.should render_template(:edit) }
  end
end

但是,我收到了这个错误。

    Failures:

  1) NewsController GET 'edit' 
     Failure/Error: it { assigns(:news).should eq(@news_1) }

       expected: #<News id: 1, title: "news_title_1", contents: "news_contents_1", display: nil, created_at: "2012-11-29 07:24:49", updated_at: "2012-11-29 07:24:49", news_date: nil, orion: false, pw: false, op: false, pickup: false, info_1: nil, info_2: nil, info_3: nil, info_4: nil, info_5: nil, del: false, place: nil, contact: false>
            got: #<News id: 1, title: "news_title_1", contents: "news_contents_1", display: nil, created_at: "2012-11-29 07:24:49", updated_at: "2012-11-29 07:24:49", news_date: nil, orion: false, pw: false, op: false, pickup: false, info_1: nil, info_2: nil, info_3: nil, info_4: nil, info_5: nil, del: false, place: nil, contact: false>

       (compared using ==)

       Diff:#<News:0x000001030b55c8>.==(#<News:0x000001033126b8>) returned false even though the diff between #<News:0x000001030b55c8> and #<News:0x000001033126b8> is empty. Check the implementation of #<News:0x000001030b55c8>.==.
     # ./spec/controllers/news_controller_spec.rb:73:in `block (3 levels) in <top (required)>'

我认为这些值相同,但对象ID不同。 所以这个测试失败了...... 我该如何解决这个错误?

4 个答案:

答案 0 :(得分:1)

我自己有这个问题。我的解决方法是比较属性,即

it { assigns(:news).attributes.should eq(News.last.attributes) }

答案 1 :(得分:0)

我认为这里的问题是'eq'如何比较两个对象。您可能希望在此方案中使用==。您可以在此question here

中查看详细说明

答案 2 :(得分:0)

你应该按照以下方式进行

要求'spec_helper'

describe NewsController do  
  describe "GET 'edit'" do
    before(:each) do
      @news_1 = FactoryGirl.create(:news_1)
      get :edit, { :id => @news_1.id }
    end
    it { response.should be_success }
    it { assigns(:news).should eq(News.last) }
    it { response.should render_template(:edit) }
  end
end

==和eq不同。要在检索对象时测试方法,请使用should ==或等效的a.should eql

答案 3 :(得分:0)

比较一个数组我遇到了这个问题,我解决了它:

expect(assigns(:receipts)).to match_array(receipts)