[rspec-users] Getting Class in Shared Behaviours

Scott Taylor mailing_lists at railsnewbie.com
Wed Nov 21 16:53:27 EST 2007


On Nov 21, 2007, at 4:22 PM, David Chelimsky wrote:

> On Nov 21, 2007 3:14 PM, Daniel N <has.sox at gmail.com> wrote:
>> Hi,
>>
>> I want to be able to get at the described class in my shared  
>> behaviour.  I'm
>> sure an example will say it better than my words
>>
>> describe "my shared", :shared => true do
>>
>>   it "should tell me what the class is its describing" do
>>     how_do_i_get_the_user_class_here
>>  end
>>
>> end
>>
>> describe User do
>>   it_should_behave_like "my shared"
>>
>>   #...
>> end
>>
>> So in my shared behaviour, how do I get access to the User class?
>
> There's no way to do this implicitly. i.e. rspec does not expose the
> class. You'd have to have a method like described_class or something:
>
> describe "my shared", :shared => true do
>
>   it "should tell me what the class is its describing" do
>     described_class.should do_something_I_care_about
>  end
>
> end
>
> describe User do
>   def described_class
>     User
>   end
>   ...
> end

Or you could just set up instance variables in your before :each block:

describe "an object which has to_s", :shared => true do
   it "should work!" do
     :foo.send(@method).should == "foo"
   end
end

describe Symbol do
   before :each do
     @method = :to_s
   end

   it_should_behave_like "an object which has to_s"
end


On another note, I've been poking around Rubinius' source, which uses  
a scaled down version of rspec, and they already have shared examples  
with parameters:

shared :symbol_id2name do |cmd|
   describe "Symbol\##{cmd}" do
     it "returns the string corresponding to self" do
       :rubinius.send(cmd).should == "rubinius"
       :squash.send(cmd).should == "squash"
       :[].send(cmd).should == "[]"
       :@ruby.send(cmd).should == "@ruby"
       :@@ruby.send(cmd).should == "@@ruby"
     end
   end
end

require File.dirname(__FILE__) + '/../../spec_helper'

describe "Symbol#to_s" do
   it_behaves_like(:symbol_id2name, :to_s)
end


This doesn't seem that hard to implement.  Is there some reason a  
patch has been created yet?

Scott




More information about the rspec-users mailing list