2

我尝试像这样使用 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

4 回答 4

1

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

it { assigns(:news).attributes.should eq(News.last.attributes) }
于 2013-06-22T14:41:52.330 回答
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

于 2012-11-29T07:50:10.450 回答
0

我认为这里的问题是'eq'如何在两个对象之间进行比较。您可能想在这种情况下使用 == 。你可以在这里看到这个问题的详细解释

于 2012-11-29T07:43:49.507 回答
0

我在比较数组时遇到了这个问题,我用以下方法解决了它:

expect(assigns(:receipts)).to match_array(receipts)
于 2016-04-17T02:33:02.513 回答