Search code examples
rspecrspec-rails

RSpec can't load my non ActiveModel model classes


I'm new to using RSpec in a Rails app and I can't get RSpec to see my Models :(

I added the following lines in my Gemfile

group :development, :test do
  gem 'rspec-rails'
end

and installed it with

rails generate rspec::install

Then I created a facebook_page.rb file in app/models/ directory, it's not an ActiveModel

class FacebookPage
  class << self
    # define class variables
    attr_accessor :app_id
    attr_accessor :app_secret
  end
end

And now I'm trying to test it so I added a facebook_page_spec.rb in spec/models/ directory

describe FacebookPage do
  describe ".app_id" do
    it "should return the FB_APP_ID environment variable and thus not be null" do
      FacebookPage.app_id.should_not be_empty 
    end
  end
end

But when I run

bundle exec rake spec

I get the following error :

/home/geoffroy/.rvm/rubies/ruby-1.9.3-p194/bin/ruby -S rspec ./spec/models/facebook_page_spec.rb
/home/geoffroy/dev/mybandpage/spec/models/facebook_page_spec.rb:1:in `<top (required)>': uninitialized constant FacebookPage (NameError)

RSpec does not seem to load my model file. Is it because it's not a subclass of ActiveRecord ? How can I solve that ?

Many thanks in advance, best

Geoffroy


Solution

  • You have a typo in rails generate rspec::install (double colon) try use rails generate rspec:install. Also try to run the test with the following command bundle exec rspec spec.

    Did you require "spec_helper" in your test?

    ps. This code is wrong:

    class FacebookPage
      class << self
        # define class variables
        attr_accessor :app_id
        attr_accessor :app_secret
      end
    end
    

    Basically in this example you're defining instance variables on the singleton class, try use this approach: http://apidock.com/rails/Class/cattr_accessor