【问题标题】:Expected Count to change by 1 but was changed by 0 - Pry within Rspec预期计数将更改 1,但更改为 0 - 在 Rspec 中撬动
【发布时间】:2019-07-18 01:30:37
【问题描述】:

所以我有以下模型:ExistingCustomer 并且所有测试都很好,并且运行良好。客户请求了几个新字段。一个是一个简单的字符串,所以我更新了。另一个是与特定区域的关联。更新了 MVC,它工作正常。它存储等。

但是,我的 rspec 在创建时失败,我无法终生弄清楚为什么/如何找到错误。

所以我的规范看起来像:

require 'rails_helper'
require 'pry'

RSpec.describe ExistingCustomersController, type: :controller do

  describe 'create' do
    it 'should create existing customer' do
      binding.pry
      expect do
        binding.pry
        post :create, params: { existing_customer: FactoryBot.attributes_for(:existing_customer) }
      end.to change(ExistingCustomer, :count).by(1)
    end
    it 'sends an email' do
      expect(ExistingCustomerMailer).to send_mail(:existing_customer_request)
      post :create, params: { existing_customer: FactoryBot.attributes_for(:existing_customer) }
    end
  end
end

FactoryBot 看起来像:

FactoryBot.define do
  factory :existing_customer do
    region
    first_name { 'Jake' }
    last_name { 'Peralta' }
    phone { '991-999-9999' }
    email { 'best.detective@ninenine.com' }
    title { 'World\'s Best Detective/Genius' }
    account_number { 99 }
    company_name { 'NYPD' }
    existing_customer_email { 'better.detective@ninenine.com' }
  end
end

我已经完成了关联 :region 和 just region。没有不同。 而不是工厂,我做了类似的事情:

let(:existing_params) 做 {first_name: 'Jake', etc}

然后通过它而不是 FactoryBot。同样的问题。

在所有情况下,它都无法创建。如何找出导致 Pry 问题的原因。我知道在 it 块中插入 binding.pry 以进行访问。我应该在撬内抓住什么来测试?在 rspec 中进行撬动测试时,我是个菜鸟。

编辑: 所以我在 create 的控制器中放了一个 binding.pry:

def create
 @existing_customer = ExistingCustomer.new(existing_customer_params)
 binding.pry
 if @existing_customer.save
  redirect_to existing_customer_success_path
 ExistingCustomerMailer.existing_customer_request(@existing_customer).deliver
else
  render 'new'
end

结束

再次运行测试并执行@existing_customers.errors。它正在返回@messages = :region=>{必须存在}

所以问题是如何在规范的参数中传递特定的关联 ID?

【问题讨论】:

  • Pry 会在某个时刻暂停执行。那么问题是:那一刻我想知道什么?在任何有意义的事情发生之前,pry pause 的前两种用法。在 POST 发生后询问现有客户的数量怎么样?
  • 有效点。所以我确实在结束前的期望之后放了一个 binding.pry 。然后我做了 ExistingCustomer.count 并且它返回 0。所以我猜在这种情况下它没有创建。
  • 好的,接下来,在该 Pry 会话中运行 post 函数。如果没有创建客户,您应该得到一个错误响应。那是什么错误?
  • 已更新。看来我需要找到一种方法在测试中传递参数中的特定关联 ID。
  • 你不需要传递一个ID,你需要提供一个区域。 region 在您的现有客户工厂中引用的是区域工厂。有这样的工厂吗?

标签: ruby-on-rails


【解决方案1】:

问题在于 attributes_for 以及与 FactoryBot 的关联。这使测试通过:

it 'should create existing customer' do
  expect do
    post :create, params: { existing_customer: FactoryBot.attributes_for(:existing_customer)
                                                         .merge(region_id: create(:region)) }
  end.to change(ExistingCustomer, :count).by(1)
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多