Reputation: 173
I try to test a rails controller with rspec like this:
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
But, I got this error.
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)>'
I think these values are same, but object id is different. So this test fails... How do I solve this error?
Upvotes: 2
Views: 2760
Reputation: 12550
I had this problem comparing an array and I solved it with:
expect(assigns(:receipts)).to match_array(receipts)
Upvotes: 0
Reputation: 1171
Had this problem myself. My workaround was comparing the attributes, i.e.
it { assigns(:news).attributes.should eq(News.last.attributes) }
Upvotes: 1
Reputation: 2385
you should do as follow
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.last) }
it { response.should render_template(:edit) }
end
end
== and eq are different. To test your method when it retrieves the object, then use should == or its equivalent a.should eql
Upvotes: 0
Reputation: 94
I think the problem here is how the 'eq' does the comparison between two objects. you might want to use == in this scenario. You can see a detailed explanation in this question here
Upvotes: 0