2014-04-17 86 views
2

測試PG數據庫約束我想使用RSpec的一個軌道4測試PG數據庫的限制,我不知道如何設置它。使用RSpec

我的想法是做這樣的事情:

before do 
    @subscriber = Marketing::Subscriber.new(email: "[email protected]") 
end 

describe "when email address is already taken" do 
    before do 
    subscriber_with_same_email = @subscriber.dup 
    subscriber_with_same_email.email = @subscriber.email.upcase 
    subscriber_with_same_email.save 
    end 

    it "should raise db error when validation is skipped" do 
    expect(@subscriber.save!(validate: false)).to raise_error 
    end 
end 

當我運行它,它在產生一個錯誤:

PG::UniqueViolation: ERROR: duplicate key value violates unique constraint 

然而,測試仍然失敗。

是否有正確的語法來獲得測試通過?

回答

4

嘗試

it "should raise db error when validation is skipped" do 
    expect { @subscriber.save!(validate: false) }.to raise_error 
end 

欲瞭解更多信息,請查看more info on rspec-expectations expect-error matchers

希望這有助於!

+0

愛是愛的語法錯誤。謝謝你的幫助! – GoBlue1616

+0

謝謝@ user2262149。你的方法比保存''更優雅,並返回ActiveRecord :: RecordNotUnique或PG :: UniqueViolation。 – scarver2