2014-02-27 52 views
3

有如下的RSpec代碼:使用期望,並應在RSpec的

it 'is not valid if name is not present' do 
    @car.name = nil 
    expect(@car).to be_invalid 
end 

由亞倫·薩姆納我讀「測試使用RSpec」現在,他寫了關於在RSpec的新款式。此前我寫了下面的代碼:

it 'is not valid if name is not present' do 
    @car.name = nil 
    it { should_not be_valid } 
end 

請告訴我,對不對?謝謝。

+0

我不知道你有什麼要求嗎?你能解釋一下你的困惑或問題嗎? – Surya

+0

我想知道我的規格是否有很好的風格? – malcoauri

+0

就是這樣。這裏:https://stackoverflow.com/questions/21437817/rails-rspec-var-should-5-or-var-should-var2-value/21438017#21438017 – Surya

回答

8

我覺得這是一個很好的例子

describe "Car" 
    describe '#valid?' do 
    context 'when its name is nil' do 
     let(:car) { FactoryGirl.create(:car, :name => nil) } 

     it 'is not valid' do 
     expect(car).to_not be_valid 
     end 
    end 
    end 
end 

查找更多關於更好的規格here

3

使用let API而不是使用@car,這樣你就不會冒險從測試更改狀態測試,可能以不可預測的方式破壞測試。

itone-linersubject所以做出你的第二個工作作風應該看起來像:

describe '#valid?' do 
    let(:car) do 
    # make your car here 
    end 

    subject { car } # <- this is the important line to make it work... 

    before do 
    car.name = nil 
    end 

    it { should_not be_valid } 
end