2011-09-28 28 views
13

我有一個這樣的試驗:斷言多種變化的預期要求

lambda { post("/api/users", parameters) }.should change(User,:count).by(1) 
lambda { post("/api/users", parameters) }.should_not change(ActionMailer::Base, :deliveries) 

但我想那樣做:

lambda { post("/api/users", parameters) }.should change(User,:count).by(1).and_not change(ActionMailer::Base, :deliveries) 

是否有可能做到這一點,而不需要兩個郵政電話?

感謝

+0

正在尋找這個我自己 – prusswan

回答

11

我找到了一個解決方案來測試它。

lambda{ 
    lambda { post("/api/users", params) }.should change(User,:count).by(1) 
}.should change(ActionMailer::Base.deliveries, :count).by(1) 
2

在我的測試,我很嚴格:我想每個測試只測試一個單一的東西。所以我會一直選擇第一種形式,而不是第二種形式。其次我不確定它在技術上是否可行。 .should需要一個在lambda之前和之後執行的塊。無論如何,據我所知目前rspec不支持這個(和imho有很好的理由)。

+0

好的,謝謝你的回覆! –

0

feature測試格式遷移時的一些request試驗水豚2.1,並從基礎的shouldexpect基於切換測試語法還有我最近碰到這個問題。要使用原來的問題爲例,我有這樣的代碼:

subject { -> { post("/api/users", parameters) } } 
it { should change(User,:count).by(1) } 
it { should_not change(ActionMailer::Base, :deliveries) } 

scenario測試將這一到expect語法提出了一些問題,並取得了這樣的(工作)clunkiness的(對不起,不是一個大風扇明確地嵌套lambda S/expect S):

expect(-> { expect(post("/api/users", parameters)).to change(User,:count).by(1) } 
).to_not change(ActionMailer::Base, :deliveries) 

有在this StackOverflow thread這個問題一些偉大的解決方案,我試圖與成功,但我落得這樣做只是按照原來的格式有點和拆出每個語句都變成了自己的scenario;是這樣的:

feature "Add users via API" do 
    given(:posting_parameters_to_api) { -> { post("/api/users", parameters) } } 

    scenario "foo" do 
    expect(posting_parameters_to_api).to change(User,:count).by(1) 
    end 

    scenario "bar" do 
    expect(posting_parameters_to_api).to_not change(ActionMailer::Base, 
                :deliveries) 
    end 
end 

比原來request規範更詳細,但以同樣的方式基本上是工作。實施可能會歸結爲個人品味。