0

Finally got around to working my way through a book about rspec and implementing some simple tests on one of my models before slowly building it up.

My model Coaster.rb - (Removed some unimportant parts)

class Coaster < ActiveRecord::Base

  extend FriendlyId
  friendly_id :slug, use: :slugged

  belongs_to :park
  belongs_to :manufacturer

  attr_accessible :name,
                  :height,
                  :speed,
                  :length,
                  :inversions,

  default_scope :order => 'name ASC'

  delegate :name, :city, :region, :country, to: :park, allow_nil: true, prefix: true
  delegate :name, :url, to: :manufacturer, prefix: true

  validates :name, :presence => true

  validates :speed,
    :allow_nil => true,
    :numericality => {:greater_than => 0}


  *def name_and_park
  *  "#{name} at #{park.name}"
  *end

  *def slug
  *  name_and_park.parameterize
  *end
end

My first simple test:

describe Coaster do

  it 'is valid with a name' do
    coaster = Coaster.new(
      name: 'Collin'
    )
    expect(coaster).to be_valid
  end

end

and the results I get when running the tests:

  1) Coaster is valid with a name
     Failure/Error: expect(coaster).to be_valid
     NoMethodError:
       undefined method `name' for nil:NilClass
     # ./app/models/coaster.rb:65:in `name_and_park'
     # ./app/models/coaster.rb:69:in `slug'
     # ./spec/models/coaster_spec.rb:9:in `block (2 levels) in <top (required)>'

If I remove the lines I have marked with the asterisk in the model, then the tests pass but what about those lines is failing the test?

4

1 回答 1

3

Exactly what it says-you're creating a Coaster with no associated Park, so the call to park.name fails.

This implies that validation is also ensuring there's a slug for the model.

于 2013-07-20T15:57:21.727 回答