2010-09-12 12 views

risposta

19

Senza molto l'hacking è possibile utilizzare eccezionale gioiello: http://github.com/carlosbrando/remarkable

Tratto da notevoli docs:

describe Post do 
     it { should belong_to(:user) } 
     it { should have_many(:comments) } 
     it { should have_and_belong_to_many(:tags) } 
    end 
+0

Very nice! Penso che potrei iniziare a usare quella gemma. –

+3

Un'altra opzione è Shoulda di thoughtbot, che ha una sintassi molto simile. http://github.com/thoughtbot/shoulda –

+0

Un aspetto notevole è più completo di Shoulda. Non l'ho visto prima. –

6

È possibile riflettere sulla classe:

MyModel.reflect_on_association(:x).macro == :has_one 

E 'probabilmente più facile se si utilizza Shoulda, ci sono metodi di supporto in modo che legge molto più pulito: it { should have_many(:x) }

1

ecco una soluzione RSpec indipendente, il chiave è quella di utilizzare reflect_on_assocation

class MyModel < ActiveRecord::Base 
    has_many :children 
    belongs_to :owner 
end 

reflection_children = MyModel.reflect_on_association(:children) 

if !reflection_children.nil? 
    if reflection_children.macro == :has_many 
    # everything is alright 
    else 
    # it's not has_many but exists 
    end 
else 
    # it doesn't exist at all ! 
end 

reflection_owner = MyModel.reflect_on_association(:owner) 

if !reflection_owner.nil? 
    if reflection_owner.macro == :belongs_to 
    # everything is alright! 
    else 
    # it's not belongs_to but exists 
    end 
else 
    # it doesn't exist at all! 
end 
Problemi correlati