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?

1 Answer 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.

Sign up to request clarification or add additional context in comments.

2 Comments

To get the park from the coaster I just do coaster.park_name as I set prefix to be true on the delegate. I'm guessing, from what you've said that to write the test correctly i need to make sure the coaster I am creating in the test has a park and then to test the coasters name?
@rctneil Oh, I missed that you'd set :prefix, sorry. But yes, since there's no park, that line will fail. So I guess the slug is part of model validation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.