RSpec嵌套路由 - NoMethodError:未定义的方法`customer'

时间:2013-10-10 15:00:39

标签: ruby-on-rails ruby-on-rails-3 rspec

我正在尝试测试嵌套路由但是我得到一个未定义的方法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只是简单地返回第一个违规行为和相关客户。

如果有人能对此有所了解,那就有兴趣了。

1 个答案:

答案 0 :(得分:1)

Alert类中的

violations.first为nil。

您没有在测试中为警报设置任何违规,因此@alert.violations将是一个空数组。在空数组上调用first为nil,并且无法在nil上调用customer

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