0

我正在尝试测试嵌套路由,但是我得到了一个未定义的方法customer for nil:NilClass。我有以下 RSpec 测试:

     let(:valid_attributes) do
    {alert_type: 'Error', subject: 'Triple-buffered responsive system engine',
     state: 'Allocated', run_date: '2013-09-30 13:56:58', priority: 1, examined_on: '2013-09-30 13:56:58'
    }
  end

  let(:valid_card_attributes) do
    {name_on_card: 'Botsford', expiration_date: '2013-09-24',
     expiration_month: '2013-09-24', valid_year: '2013-09-24', valid_month: '2013-09-24',
     card_number: '2456-6996-2785-3769', bin: '8384-0294'
    }
  end


  let(:valid_violation_attributes) do
    {internal_code: 'Subsche', rule_priority: '96',
     rule_id: '10', account_id: '10',
     authorisation_id: '356'
    }

  end


  let(:valid_customer_attr) do
    { first_name: 'CustomerString', last_name: 'CustomerString',
       address1: 'CustomerString' , address2: 'CustomerString', post_code: 'CustomerString',
       telephone: 'CustomerString', country: 'CustomerString', member_id: 1,
       merchant_id: 1
     }
  end

  let(:valid_session) { {} }

  context 'JSON' do
    describe 'GET show' do
      it "delivers an alert with ID in JSON when a user requests '/api/alerts/id'" do
        alert = Alert.create! valid_attributes
        get :show, {:id => alert.to_param}, :format => :json
        assigns(:alert).should eq(alert)
      end
    end
    describe 'GET customer'
    it 'delivers an alert with a customer and associated card' do
      alert = Alert.create! valid_attributes
      customer = Customer.create! valid_customer_attr
      card = Card.create! valid_card_attributes.merge(customer_id: customer.id)
      Violation.create! valid_violation_attributes.merge(alert_id: alert.id, customer_id: customer.id)

      get :customer, {:id => alert.to_param}, :format => :json
      assigns(:alert).customer.cards.first.should eq(card)
    end
  end
end

我回来的错误的 console.log 是:

NoMethodError: undefined method `customer' for nil:NilClass
./app/models/alert.rb:10:in `customer'
./app/controllers/alerts_controller.rb:22:in `customer'
./spec/controllers/alerts_controller_spec.rb:33:in `block (3 levels) in <top (required)>'

这样做violation.first.customer只是简单地返回第一次违规和相关的客户。

如果有人能对此有所了解,请感兴趣。

4

1 回答 1

1

violations.first在您的警报课程中为零。

您没有在测试中为您的警报设置任何违规行为,因此@alert.violations将是一个空数组。调用first一个空数组是 nil,你不能调用customernil。

您可以使用try(例如violations.first.try(:customer))来解决此问题,或者更正确地检查是否存在任何违规行为(例如violations.first.customer if violations.any?)。

于 2013-10-10T15:03:56.990 回答