【问题标题】:RSPEC error: expected #<> got #<> (compared using ==) - Ruby on RailsRSPEC 错误:预期 #<> 得到 #<>(使用 == 比较)- Ruby on Rails
【发布时间】:2015-05-05 21:32:19
【问题描述】:

我正在使用 RSPEC 在 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 ==)

我不明白,“预期”和“得到”部分似乎是同一件事!有什么想法/请帮忙?

【问题讨论】:

    标签: ruby-on-rails testing rspec controller factory-bot


    【解决方案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
    

    ...类似的东西。

    【讨论】:

      【解决方案2】:

      由于两个对象都没有保存,并且您不想测试它们是否完全相同,您可以检查它们的属性是否匹配,比较将在两个哈希之间进行

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-16
        • 1970-01-01
        • 1970-01-01
        • 2014-01-01
        • 2014-03-20
        相关资源
        最近更新 更多