Topic: [rSpec] Controller should set a certain Variable

Hey All,

I am hoping this is a quick question, it has had me stumped for ages know and am hoping you can put an end to my misery!

Basically, I have the following spec:

describe TopicsController, 'handling GET /community/testing/new-topic' do
  before do
    @topic = mock_model(Topic)
    @board = mock_model(Board)
    Topic.stub!(:new).and_return(@topic)
    Board.stub!(:find_by_url).and_return(@board)
  end
 
  def do_get
    get :new
  end
 
  it "should be successful" do
    do_get
    response.should be_success
  end
 
  it "should render new template" do
    do_get
    response.should render_template('new')
  end
 
  it 'should find the current board' do
    Board.should_receive(:find_by_url).and_return(@board)
    do_get
  end
 
  it "should assign the board for the view" do
    do_get
    assigns[:board].should equal(@board)
  end
 
  it "should create a new topic" do
    Topic.should_receive(:new).and_return(@topic)
    do_get
  end
 
  it "should assign the new topic for the view" do
    do_get
    assigns[:topic].should equal(@topic)
  end
 
  it 'should assign set the board_id of the new topic to the id of the current board'
 
end

You can see the last example has not yet been implemented.

The controller action that this spec is for is simply:

def new
  @board = Board.find_by_url(params[:board])
  @topic = Topic.new
  @topic.board_id = @board.id
end

But I have no idea how to write a spec for the last line. I assume it should be pretty simple, but as I am so new to this I am at a loss!

Please help me out guys

Andy

Re: [rSpec] Controller should set a certain Variable

assigns[:topic][:board_id].should eql(@board.id)

perhaps

Re: [rSpec] Controller should set a certain Variable

Hey Radar, I tried that but no luck, "You have a nil object when you didn't expect it!" any other ideas?

I am wondering whether I need to stub out @topic.board_id and @board.id but I am not really sure.

Re: [rSpec] Controller should set a certain Variable

Right, I solved it!

It dawned on me that calling @topic.board_id = 'something' is actually calling a setter method (I think that is the correct ruby term) so rather than stubbing :board_id you actually need to stub :board_id= and make sure the controller issues a call to that.

Below is the final spec, I removed the other examples to focus on what matters.

describe TopicsController, 'handling GET /community/testing/new-topic' do
  before do
    @topic = mock_model(Topic)
    @board = mock_model(Board)
    Topic.stub!(:new).and_return(@topic)
    Board.stub!(:find_by_url).and_return(@board)
   
    @topic.stub!(:board_id=).and_return(@board.id)
  end
 
  def do_get
    get :new
  end

  #... other examples here...
 
  it 'should set the board_id of the new topic to the id of the current board' do
    @topic.should_receive(:board_id=).with(@board.id).and_return(@board.id)
    do_get
  end
 
end

Last edited by andypearson (2007-07-24 13:41:36)