【问题标题】:Why is my Ruby on Rails RSpec test passing with both @plugin and @plugins?为什么我的 Ruby on Rails RSpec 测试同时通过 @plugin 和 @plugins?
【发布时间】:2010-06-04 16:36:26
【问题描述】:

我在 Foundation Rails 2 书的第 10 章。我们正在与 RSpec 合作。

我们正在测试“PluginsController”的“索引”操作。

这是控制器的代码:

    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

这是该控制器的测试代码:

    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

当我们编写测试时,我认为这一行

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

应该有

@plugins

而不是

@plugin

因为在控制器中我们有

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

我想看看如果我改变了会发生什么

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

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

测试通过了。

那么...为什么是@plugin 而不是@plugins?还有...为什么两个都通过测试?

干杯!

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    当你有一个未定义的变量时,就像@plugins 一样,因为你没有在测试的早期定义它,它会显示为 nil。

    Plugin.should_receive(:find).with(:all).and_return([@plugins]) 在这种情况下实际上做的是告诉Plugin.find(:all) 返回[nil],根据您的测试,这是有效的。

    【讨论】:

    • 好的,这是有道理的。谢谢,吉米。不过,我仍然想知道...在“PluginsController”中,我们有 def index @plugins = Plugin.find(:all) 那么为什么我们不在测试中使用 @plugins 呢?为什么我们在 @plugin = mock_model(Plugin) 中使用 @plugin?
    • 好吧,这取决于你。它只是测试中使用的一个实例变量,因此您可以选择所需的名称。也许更好的名字是@mocked_plugin。我猜他们在书中称它为@plugin 而不是@plugins 的原因是因为它不是一个模拟数组(只有一个实例,因此没有复数)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多