2015-05-16 24 views
6

olduğundan emin olun Yeni programlayıcı burada. Projemde Reddit klonu olan bir öğrenciyim. Şu anda RSPEC'e tanıtıldım. Diğer alıştırmalarda kullanılmak üzere kendi Model testlerimi yazmaya başlamak zorundayım. Söz konusu model oluşturulmadı, bir sonraki ödevde olacak. Birisi bunu doğru yapıp yapmadığımı kontrol edebilir mi?İlk RSPEC testi, değerin 1 veya -1

In the next checkpoint, we'll add a Vote model. This model will feature an inclusion validation. Inclusion validation ensures that a vote's value attribute is either 1 or -1. If a vote is initialized with any other value, it will not save.

  1. Create VoteSpec:

Spec/modeller/vote_spec.rb

describe Vote do 
    describe "validations" do 
    describe "value validation" do 
     it "only allows -1 or 1 as values" do 
     # your expectations here 
     end 
    end 
    end 
end 

Write a spec that asserts the validations work as expected.

Use RSpec's expect().to eq() syntax. As you may recall from the specs in the Ruby exercises, you can assert that something should equal false or true.

You won't be able to run the tests because we haven't generated the model we're testing.

Aşağıda benim uygulamasıdır:

describe Vote do 
    describe "validations" do 

    before do  
     2.times { @vote.create(value: 1) } 
     3.times { @vote.create(value: -1) } 
     2.times { @vote.create(value: 3) } 
    end 

    describe "value validation" do 
     it "only allows -1 or 1 as values" do 
     expect (@vote.value).to eq(-1) 
     end 

     it "only allows -1 or 1 as values" do 
     expect (@vote.value).to eq(1) 
     end 
    end 
    end 
end 

Saygılarımızla.

Düzenleme:

describe Vote do 
    describe "validations" do 

    before do  
     2.times { Vote.create(value: 1) } 
     3.times { Vote.create(value: 0) } 
     2.times { Vote.create(value: 3) } 
    end 

    describe "value validation" do 
     it "only allows -1 as value" do 
     expect (@vote.value).to eq(-1) 
     end 
     it "only allows 1 as value" do 
     expect (@vote.value).to eq(1) 
     end 

     it "it prohibits other values" do 
     expect(@vote.value).to_not be_valid 
     end 
    end 
    end 
end 

Ben de ilk başta çalıştı bu kod ile çalıştı ama şimdi bir sonraki atama başarısız olması: Bu biraz özel durumda

require 'rails_helper' 

    describe Vote do 
    describe "value validation" do 

     it "allows -1" do 
     value = Vote.create(value: -1) 
     expect(value).to be_valid 
     end 

     it "allows +1" do 
     value = Vote.create(value: +1) 
     expect(value).to be_valid 
     end 

     it "prohibits other values" do 
     value = Vote.create(value: 0) 
     expect(value).to_not be_valid 
     end 

    end 
end 

▶ rspec spec 
...FFF 

Failures: 

    1) Vote value validation allows -1 
    Failure/Error: value = Vote.create(value: -1) 
    NoMethodError: 
     undefined method `update_rank' for nil:NilClass 
    # ./app/models/vote.rb:12:in `update_post' 
    # ./spec/models/vote_spec.rb:7:in `block (3 levels) in <top (required)>' 

    2) Vote value validation allows +1 
    Failure/Error: value = Vote.create(value: +1) 
    NoMethodError: 
     undefined method `update_rank' for nil:NilClass 
    # ./app/models/vote.rb:12:in `update_post' 
    # ./spec/models/vote_spec.rb:12:in `block (3 levels) in <top (required)>' 

    3) Vote value validation prohibits other values 
    Failure/Error: expect(value).to eq(false) 

     expected: false 
      got: #<Vote id: nil, value: 0, user_id: nil, post_id: nil, created_at: nil, updated_at: nil> 

     (compared using ==) 
    # ./spec/models/vote_spec.rb:18:in `block (3 levels) in <top (required)>' 

Finished in 0.30485 seconds (files took 3.28 seconds to load) 
6 examples, 3 failures 

Failed examples: 

rspec ./spec/models/vote_spec.rb:6 # Vote value validation allows -1 
rspec ./spec/models/vote_spec.rb:11 # Vote value validation allows +1 
rspec ./spec/models/vote_spec.rb:16 # Vote value validation prohibits other values 
+0

'@ vote.create' başarısız olacak @ oyu yok. Sanırım sen oy ver demek istiyorsun. –

+0

Teşekkürler @AndyWaite Bu mantıklı. Bunun dışında testim iyi görünüyor mu? –

+0

Diğer bazı sorunlar var. Örneğin, "beklediğiniz" ifadeleriniz aynı sonucu kontrol ediyor, ancak her durumda farklı değerler bekliyorsunuz. –

cevap

3

İşte revizyon olduğunu mutlak değeri kullanabilirsiniz.

it "only allows -1 or 1 as values" do 
    expect (@vote.value.abs).to eq(1) 
end 
+0

Bunu yapmakla ilgili iyi bir şey yok. Her iki durumda da "1" ve "-1" olarak ayarlandığında "değer" 1'e eşitse ne olur? Bu test size bundan bahsetmeyecek. Testlerinize mantık koymayın, sadece onları akılda zorlaştırır ve hatalara yol açar. – hakcho

+0

Bu, – iGbanam

2

Sen or ile RSpec compound expectations kullanabilirsiniz:

it "only allows -1 or 1 as values" do 
    expect (@vote.value).to eq(1).or eq(-1) 
end 
+0

'u test etmenin iyi bir yolu Teşekkürler! Bu şekilde okumayı tercih ederim. "Başka bir değerle bir oylama başlatılırsa, kaydedilmez" ifadesini okur musunuz? Bu testin amacı için başka bir ifade oluşturmak zorunda mıyım? –

1

Jonathan, senin talimatlarına göre, sen/kaydetme oyu doğrulamak ve sonuç doğru veya yanlış olup olmadığını görmek için çalışıyor olmalıdır. Kodunuzu daha temiz bir hale getirmek için let ve build numaralı belgeleri de kullanmanız gerekir; oysa, açık bir şekilde bunu yapana kadar oylamanın kaydedilmediğinden emin olun.

This model will feature an inclusion validation. Inclusion validation ensures that a vote's value attribute is either 1 or -1. If a vote is initialized with any other value, it will not save.

Let en:

describe Vote do 
    describe "validations" do 
    let(:vote) { Vote.new(value: vote_value) } 

    context "when the value is 1" do 
     let(:vote_value) { 1 } 

     it "successfully saves" do 
     expect(vote.save).to eq(true) 
     end 
    end 

    context "when the value is -1" do 
     let(:vote_value) { -1 } 

     it "successfully saves" do 
     expect(vote.save).to eq(true) 
     end 
    end 

    context "when the value is 0" do 
     let(:vote_value) { 0 } 

     it "does not save" do 
     expect(vote.save).to eq(false) 
     end 
    end 
    end 
end 

teste görev kendisinde zaten ne olduğunu bana öyle geliyor vote.valid?

+0

Bana yardım etmek için zaman ayırdığınız için teşekkür ederim. Bu kod benim için çok okunabilir. Ne yazık ki, bu da başarısız oluyor, Hata/Hata: let (: oy) {Vote.build (value: vote_value)} NoMethodError: undefined metot # oluşturmak için

+0

Üzgünüz, genellikle 'build' kullanın Nesneyi yaratmak istemediğimde fabrika kızıyla. Ben sadece şimdi çalışması gereken bir şeye güncelledim, 'Vote.new' – JSFernandes

+0

kullanarak 0 değeri için satırı değiştirmek isteyebilirsiniz: "kaydetmez" için "başarıyla kaydeder". – floum

0

tarafından bu vote.save yerine çekinmeyin: İşte bu durumun üstesinden nasıl olduğunu adım adım yürüme:

describe Vote do 
    describe 'validations' do 
    it 'should treat -1 vote value as valid' do 
     # 1. Prepare the environment. That comes right from the task: we need 
     # to create a model with a vote value of -1. 
     # 2. Do something. Again, from the task: let's try saving it. 
     # 3. Verify the result. From the tasks again: it should save. 
    end 
    end 
end 

Şimdi biliyoruz ne yapmak, gidip biraz kod yazalım:

describe Vote do 
    describe 'validations' do 
    it 'should treat -1 vote value as valid' do 
     # 1. Prepare the environment. That comes right from the task: we need 
     # to create a model with a vote value of -1. 
     vote = Vote.new(value: -1) 

     # 2. Do something. Again, from the task: let's try saving it. 
     result = vote.save 
     # (according to ActiveRecord specifications `.save` returns 
     # `true` when it succeeds saving, and `false` otherwise. 

     # 3. Verify the result. From the tasks again: it should save. 
     expect(result).to be_true 
    end 

    it 'should treat 1 vote value as valid' do 
     # Prepare the environment 
     vote = Vote.new(value: 1) 
     # Do something 
     result = vote.save 
     # Verify the result 
     expect(result).to be_true 
    end 

    it 'should treat 0 vote value as invalid' do 
     # Prepare the environment 
     vote = Vote.new(value: 0) 
     # Do something 
     result = vote.save 
     # 3. Verify the result. From the task: it should *not* save. 
     expect(result).to be_false 
    end 
    end 
end 

Şimdi uygun gerekiyor koduna sahip: o modeli doğrular.onunla sorunların bir çift vardır:

    Bu durumda başarısız olur
  • başka doğrulamaları Bu gözlük yazılır yol değil value alanda
  • yanında bulunmaktadır
  • Bu biraz ayrıntılı
  • var

edelim adresi olanlar (ı yorum şerit olacak):

describe Vote do 
    describe 'validations' do 
    let(:overrides) { { } } 
    let(:params) { { value: 1 }.merge(overrides) } # valid by default 
    subject { Vote.new(params).save } 

    context 'vote == -1 is valid' do 
     let(:overrides) { { value: -1 } } # override one parameter 
     it { is_expected.to be_true } 
    end 

    context 'vote == 1 is valid' do 
     let(:overrides) { { value: 0 } } 
     it { is_expected.to be_true } 
    end 

    context 'vote == 0 is invalid' do 
     let(:overrides) { { value: 0 } } 
     it { is_expected.to be_false } 
    end 
    end 
end 

Sen c Bunu en az iki yolla daha temiz ve daha okunabilir hale getirin: İhtiyaç duyduğunuzda:

  1. Kendi RSpec yardımcılarınızı hazırlayın.
  2. Sizin için önceden yazılan yardımcıları barındıran üçüncü taraf kitaplıklarını kullanın. Doğrulama doğrulama kodunuzu şu gibi bir şeye dönüştürürler:

    describe Vote do 
        it { is_expected.to validate_inclusion_of(:value).in_array([-1, 1]) } 
    end 
    

    Neat, huh? :) Ama bence bu alıştırmada sizden beklenen şey bu değil.

Bu yardımcı olur umarız!