开发者

Why is my Ruby on Rails RSpec test passing with both @plugin and @plugins?

I'm in Chapter 10 of the Foundation Rails 2 book. We're working with RSpec.

We're testing the 'index' action of the 'PluginsController'.

Here's the code for the controller:

    class PluginsController < ApplicationController
      # GET /plugins
      # GET /plugins.xml
      def index
        @plugins = Plugin.find(:all)

        respond_to do |format|
          format.html # index.html.erb
          format.xml  { render :xml => @plugins }
        end
      end

Here's the code for the tests for that controller:

    require File.dirname(__FILE__) + '/../spec_helper'

describe PluginsController, " GET to /plugins" do

  before do
    @plugin = mock_model(Plugin)
    Plugin.stub!(:find).and_return([@plugin])
  end

  it "should be successful" do
    get :index
    response.should be_success
  end

  it "should find a list of all plugins" do
    Plugin.should_receive(:find).with(:all).and_return([@plugin])
    get :index
  end


  it "should assign the list of plugins to a variable to be used in the view" 


  it "should render the index template" 

end

When we were writing our test, I thought that this line

Plugin.should_receive(:find).with(:all).and_return([@plugin])

should have had

@plugins

and not

@plugin

because in the controller we have

def index
@plugins = Plugin.find(:all)

I wanted to see what would happen if I changed

Plugin.should_receive(:find).with(:all).and_return([@plugin])

to

Plugin.should_receive(:find).with(:all).and_return([@plugins])

and the test pa开发者_StackOverflowssed.

So...why is it @plugin and not @plugins? And...why does the test pass with both?

Cheers!


When you have an undefined variable, as @plugins is since you don't define it earlier in the test, it will show up as nil.

What Plugin.should_receive(:find).with(:all).and_return([@plugins]) actually do in this case is that it tells Plugin.find(:all) to return [nil], which according to your test is valid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜