2011-12-05 17 views
5

私は次のコードを持っている:カテゴリによって分割され、例外TypeError:間違った引数のString型(予想モジュール)

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 

基本的にルックアップデータのロードが含まれています。目的は、データベース内の各カテゴリのメソッドを作成することです。 Railsコンソールを介して、このコードは正常に動作します。

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

しかし、私の仕様は失敗しています。以下のスペック:

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 

がで失敗します。

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

ここでの問題は何ですか?

+0

私たちはinclude-lineを表示します。それがどこにあっても。 –

答えて

0

これが動作しない理由のカップルがあります::

  • 暗黙の被験者は、あなたは、コンテキスト、またはあなたの例の周りitブロックを必要とする静的メソッド
  • で動作するように表示されません。

このコードは動作します:

require "spec_helper" 

describe ProfileLookup do 

    it 'should know what lookups are available' do 
    ProfileLookup.available_genders.should include("Male") 
    ProfileLookup.available_age_groups.should include("0-17") 
    ProfileLookup.available_interests.should include("Autos & Vehicles") 
    ProfileLookup.available_countries.should include("United States") 
    end 

end 
0

includeメソッドは通常、モジュールをクラス(または別のモジュール)に含めるために使用されます。彼らはdescribeスコープでincludeを上書きせず、itスコープ内にしかないように見えます。

3

まず、itsのためのあなたの構文が間違っている、あなたはuse the block formべき:

:あなた describeクラスは、あなたが一致している被写体が インスタンスそのクラスのがある第二

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

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.

あなたが明示的にaには試してみると、すべてがうまくいくでしょう:

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 
+0

+1。記述されたヘルパーさえあります。したがって、サブジェクトはsubject {describe_class}のようなものになる可能性があります。 – lucapette

+0

FYI - これを試しましたが、うまくいきませんでした。 –

関連する問題