views:

81

answers:

1

For example, let's say I have a Question model, that has the boolean fields answered and closed. How would I test the behavior that a Question should be read only when marked as answered using RSpec? This seems like it's the behavior of the model, but I'm not sure how to best test it. Should I be using a before filter for this behavior, and adding an error saying you can't modify an answered question? Or is there a better way to do it? I'm only learning RSpec and BDD.

+2  A: 

depends how you need it work, but...

describe Question do
  it "should be read only when marked as answered" do
    question = Question.new(:title => 'old title')
    question.answered = true
    question.save

    # this
    lambda {
      question.title = 'new title'
    }.should raise_error(ReadOnlyError)

    # or
    question.title = 'new title'
    question.save
    question.title.should == 'old title'

    # or
    quesiton.title = 'new title'
    question.save.should be_false
  end
end

Or perhaps you want the error to be raised on save? Or maybe there is no error and it just silently doesn't change the value? It's up to you how you want to implement it, but the methodology is the same.

  1. Setup your objects in the state you want to spec them
  2. Make sure your objects in that state do what you expect

So setup an answered question, and then see if you can change one its data. If you can't, then spec passed. It's up to you how you want the behaviour of your model to work. And the great thing about BDD is you think about this interface first, since you have to actually use an objects API in order to spec it out.

Squeegy