1

我想爲sti子類上的方法構建一個rspec測試,測試只讀取父模型的方法。該方法在應用程序中工作,而不是在rspec測試中。我想不出什麼我失蹤rspec測試子類sti方法rails 4

模型/動物/ animal.rb

class Animal < ActiveRecord::Base 

    def favorite 
    "unicorn" 
    end 

end 

模型/動物/ mammal_animal.rb

class MammalAnimal < Animal 

    def favorite 
    "whale" 
    end 

end 

模型/動物/ cat_mammal_animal.rb

class CatMammalAnimal < MammalAnimal 

    def favorite 
    "tabby" 
    end 

end 

mammal_animal_spec.rb

require 'rails_helper' 

RSpec.describe MammalAnimal, type: :model do 

    let(:cat_mammal_animal) {FactoryGirl.create(:cat_factory)} 
    subject(:model) { cat_mammal_animal } 
    let(:described_class){"MammalAnimal"} 

    describe "a Cat" do 
    it "should initialize successfully as an instance of the described class" do 
     expect(subject).to be_a_kind_of described_class 
    end 

    it "should have attribute type" do 
     expect(subject).to have_attribute :type 
    end 

    it "has a valid factory" do 
     expect(cat_mammal_animal).to be_valid 
    end 

    describe ".favorite " do 
     it 'shows the favorite Cat' do 
     expect(cat_mammal_animal.type).to eq("CatMammalAnimal") 
     expect(cat_mammal_animal.favorite).to include("tabby") 
     expect(cat_mammal_animal.favorite).not_to include("whale") 
     expect(cat_mammal_animal.favorite).not_to include("unicorn") 
     print cat_mammal_animal.favorite 
     end 
    end 
    end 
end 

錯誤

Failures: 
    1) MammalAnimal.favorite and .favorite shows the favorite Cat 
    Failure/Error: expect(cat_mammal_animal.type).to include("tabby") 
     expected "unicorn" to include "tabby" 
    # ./spec/models/mammal_animal_spec.rb:82:in `block (3 levels) in <top (required)>' 

UPDATE

animals.rb

FactoryGirl.define do 
    factory :animal do 
    type 'Animal' 
    name "dragon" 


    trait :mammal do 
     type 'MammalAnimal' 
     name "zebra" 
    end 

    trait :cat do 
     type 'CatMammalAnimal' 
     name "calico" 
    end 

    factory :mammal_factory, traits: [:mammal] 
    factory :cat_factory, traits: [:cat] 

    end 

end 

按照一個建議,我添加了以下行到測試

期望(cat_mammal_animal .class.constantize).to eq(CatMa mmalAnimal)

,並得到這個錯誤

1)MammalAnimal.favorite和.favorite表示最喜歡的貓 故障/錯誤:期待(cat_animal_mammal.class.constantize)。爲了EQ(CatMammalAnimal)

NoMethodError: 
    undefined method `constantize' for #<Class:0x007f8ed4b8b0e0> 
    Did you mean? constants 
+0

你的對象,當您添加預期(cat_mammal_animal.class.constantize)。爲了EQ(CatMammalAnimal會發生什麼)到你期望的失敗線以上?你也可以發佈你的工廠? –

+0

我已經更新了它,但我不確定你想要用新的線測試。 – NothingToSeeHere

+0

哎呀,我猜的是constantize位。我的理論是,你的工廠以某種方式創建了正確類型的對象,但錯誤的類。你可以將常量部分取出並使CatMammalAnimal成爲一個字符串。 –

回答

1

我認爲,而不是使用trait來創建子類的對象,你應該有這些單獨的工廠。

factory :animal do 
    name 'dragon' 
end 

factory :mammal, class: MammalAnimal do 
    name 'zebra' 
end 

factory :cat, class: CatMammalAnimal do 
    name 'calico' 
end 

所有這些都可以在animals.rb

定義然後你就可以創建一個像

create(:animal) 
create(:mammal) 
create(:cat) 
+0

我不知道爲什麼這個工作,但它確實。 – NothingToSeeHere