0

I'm currently testing this class in Sinatra/Datamapper

class Score 
include DataMapper::Resource

property :score, Integer

property :created_at, DateTime, :default => DateTime.now, :lazy => [:show]
property :updated_at, DateTime, :default => DateTime.now, :lazy => [:show]

belongs_to :pageant, :key => true
belongs_to :candidate, :key => true
belongs_to :category, :key => true
belongs_to :judge, :key => true

end

with this rspec test

it 'that can be inserted by a judge if a pageant is active' do
        score_count = Score.all.length
        post '/score', @correct_score_data
        Score.all.length.should eq score_count+1
    end

    it 'cannot be duplicated if it has been sent' do
        score_count = Score.all.length
        post '/score', @correct_score_data
        Score.all.length.should eq score_count
    end

basically what is supposed to happen is that a judge can only send a score for a specific category+candidate+pageant combination once, after which I'm suppose to deny the next scores. Now when I run this I get an IntegrityError (which I expect). How do I tell rspec that I "expect to see this error"? You guys can also critique my code, I'm still learning all of these together

Daryll Santos
  • 2,031
  • 3
  • 22
  • 40
  • 1
    This will be helpful: http://stackoverflow.com/questions/1722749/how-to-use-rspecs-should-raise-with-any-kind-of-exception – cortex Aug 21 '13 at 23:38

1 Answers1

0

Use expect{}.to raise_error: https://www.relishapp.com/rspec/rspec-expectations/v/2-6/docs/built-in-matchers/raise-error-matcher

I don't fully understand your specs (it looks like your application state is leaking between the two tests), but something like this...

it 'cannot be duplicated if it has been sent' do
    score_count = Score.all.length
    expect { post '/score', @correct_score_data }.to raise_error(IntegrityError)
end
Nick Veys
  • 23,458
  • 4
  • 47
  • 64
  • Tried it and yeah it works now. What do you mean the application state is leaking between the two tests? – Daryll Santos Aug 22 '13 at 17:32
  • Well, the two specs you posted look like they do the exact same thing, but expect different results. Unless there's more information you didn't post, I assumed you expect one test to run, succeed, and then the next test to run and push the application into the "bad" state. Two specs shouldn't require each other to work. If that's not that case, then I just assumed too much! – Nick Veys Aug 22 '13 at 17:44
  • Ah yeah what was supposed to happen was that send one, it works, send the same thing, it doesn't work... guess I need to read more – Daryll Santos Aug 22 '13 at 19:34