Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: wrong argument type String (expected Module)

I have the following code:

class ProfileLookup < ActiveRecord::Base
  class << self
    ProfileLookup.select("DISTINCT category").map{|c| c.category}.each do |category|
      define_method("available_#{category.pluralize}".to_sym) do
        ProfileLookup.where(category: category).order(:value).all.collect{|g| g.value}
      end
    end
  end
end

which basically contains a load of lookup data, split out by category. The aim is to create a method for each category in the database. Via Rails console, this code works as expected:

ruby-1.9.3@hub :002 > ProfileLookup.available_genders
  ProfileLookup Load (0.6ms)  SELECT "profile_lookups".* FROM "profile_lookups" WHERE "profile_lookups"."category" = 'gender' ORDER BY value
 => ["Female", "Male"] 

However, my specs are failing. The following spec:

require "spec_helper"

describe ProfileLookup do

  its(:available_genders).should include("Male")
  its(:available_age_groups).should include("0-17")
  its(:available_interests).should include("Autos & Vehicles")
  its(:available_countries).should include("United States")

end

fails with:

Exception encountered: #<TypeError: wrong argument type String (expected Module)>
backtrace:
/Users/fred/code/my_app/spec/models/profile_lookup_spec.rb:5:in `include'

what is the problem here?

like image 916
Neil Middleton Avatar asked Dec 05 '11 12:12

Neil Middleton


1 Answers

Firstly, your syntax for its is wrong, you should use the block form:

its(:available_genders) { should include("Male") }

Secondly, when you describe a class, the subject you're matching is an instance of that class:

https://www.relishapp.com/rspec/rspec-core/docs/subject/implicit-subject:

If the first argument to the outermost example group is a class, an instance of that class is exposed to each example via the subject() method.

You can be explicit about the subject and everything will work:

require "spec_helper"

describe ProfileLookup do

  subject { ProfileLookup }

  its(:available_genders) { should include("Male") }
  its(:available_age_groups) { should include("0-17") }
  its(:available_interests) { should include("Autos & Vehicles") }
  its(:available_countries) { should include("United States") }

end
like image 183
Gareth Avatar answered Nov 14 '22 19:11

Gareth