2015-05-05 61 views
0

我正在使用RSPEC在rails上測試我的控制器。這裏是控制器動作我測試(的相關部分),RSPEC error:expected#<> got#<>(使用==進行比較) - Ruby on Rails

控制器代碼:

before do 
    @company=FactoryGirl.create(:company) 
    @customer=FactoryGirl.create(:customer, company_id: @company.id) 
    @job=FactoryGirl.create(:job, customer_id: @customer.id, company_id: @company.id) 
    end 

class JobsController < ApplicationController 
    def new 
    if params[:customer_id] 
     @job = current_member.company.jobs.new(
     customer_id: params[:customer_id], 
     lead_id: params[:lead_id] 
    ) 
    else 
     ... 
    end 
    ... 
    end 

RSPEC代碼:

it "has valid job with customer_id param" do 
     get :new, {:customer_id=>@customer.id, :lead_id=>@job.lead_id} 
     expect(assigns(:job)).to eq @member.company.jobs.new(customer_id:@customer.id, lead_id:@job.lead_id) 
    end 

這裏是我的錯誤得到:

Failures: 

    1) Failure/Error: expect(assigns(:job)).to eq @member.company.jobs.new(customer_id:@customer.id, lead_id:@job.lead_id) 

    expected: #<Job id: nil, name: nil, status: "pending", company_id: 43, account_id_old: nil, job_type_id: nil, address_id: nil, trade_id: nil, lead_id: nil, started_date: nil, end_date: nil, created_at: nil, updated_at: nil, order_number: nil, creator_id: nil, account_id: nil, customer_id: 22, contact_id: nil> 
     got: #<Job id: nil, name: nil, status: "pending", company_id: 43, account_id_old: nil, job_type_id: nil, address_id: nil, trade_id: nil, lead_id: nil, started_date: nil, end_date: nil, created_at: nil, updated_at: nil, order_number: nil, creator_id: nil, account_id: nil, customer_id: 22, contact_id: nil> 

    (compared using ==) 

我沒有得到它,'預期'和'得到'部分似乎是同一件事!想法/幫助嗎?

回答

1

只是因爲數據是相同的,並不意味着它們是同一個對象(它們不是)。

你真的需要檢查的各種事情對你指定的對象分別,例如:

before { get :new, { customer_id: @customer.id, lead_id: @job.lead_id } } 

subject(:job) { assigns :job } 

it { is_expected.to be_a_new Job } 

it "should have the right customer_id" do 
    expect(job.customer_id).to eq @customer.id 
end 

it "should have the right lead_id" do 
    expect(job.lead_id).to eq @job.lead_id 
end 

...類似的東西。

0

由於這兩個對象都不會被保存,你真的不想要測試,如果他們是完全一樣的對象,你可以檢查它們的屬性相匹配,則比較將兩個散列

it "has valid job with customer_id param" do 
    get :new, {:customer_id=>@customer.id, :lead_id=>@job.lead_id} 
    expect(assigns(:job).attributes).to eq @member.company.jobs.new(customer_id:@customer.id, lead_id:@job.lead_id).attributes 
end 
之間
相關問題