rspec没有收到保存方法

时间:2010-08-28 17:06:06

标签: testing rspec authlogic

我对rails非常陌生,我一直在社区中关注很多很棒的教程和示例,所以首先要感谢你!

我的测试代码出了问题。该应用程序可以工作,我可以从拖尾测试数据库正在编写的日志中看到,但由于某种原因,它没有正确返回save方法。

这基本上是出自Michael Hartl的Rails Tutorial

“成功”案例正在返回“预期保存但收到它0次”,并且“失败案例重定向到错误的地方。看起来它似乎忽略了if / else块。

以下是控制器规范和控制器的相关代码

我真的很感激任何对此的见解。

谢谢, -Joe


class WebsitesController < ApplicationController
  before_filter :require_user, :only => [:new, :edit, :create, :destroy]

  def new
    @website = Website.new
    @title = "Add New Website"
  end

  def edit
    @website = Website.find(params[:id])
    @title = "Edit Website"
  end

  def create
    @website = current_user.websites.build(params[:website])
    if @website.save
      flash[:success] = "Website Added!"
      redirect_to(profile_url)
    else
      render 'new'
      @title = "Add New Website"
    end
  end

  def destroy

  end

end

require 'spec_helper'

describe WebsitesController do
  integrate_views

  describe "POST 'create'" do

    before(:each) do
      activate_authlogic
      @user = Factory(:user)
      UserSession.create(@user, true)
      @attr = {
        :domain => "http://www.example.com",
        :description => "example site"
      }
      @website = Factory(:website, @attr.merge(:user => @user))
      @user.websites.stub!(:build).and_return(@website)
    end

    describe "failure" do

      before(:each) do
        @website.should_receive(:save).and_return(false)
      end

      it "should render the 'new' page" do
        post :create, :website => @attr
        response.should render_template('websites/new')
      end
    end

    describe "success" do

      before(:each) do
         @website.should_receive(:save).and_return(true)
      end

      it "should redirect to the profile page" do
        post :create, :website => @attr
        response.should redirect_to(profile_url)
      end

      it "should have a flash message" do
        post :create, :website => @attr
        flash[:success].should =~ /website added/i
      end
    end
  end
end

1 个答案:

答案 0 :(得分:2)

在您应该使用should_receive时,我认为您正在使用stub。我自己也在努力解决这个问题:

use mocks/stubs when you DON'T want to test something
use message expectations when you DO want to test something

在您的情况下,您想要测试页面是否已呈现,请求是否已重定向,并且已设置闪存。因此,您可以根据这些条件设置消息期望您不想测试模型是否已保存或未保存,因此您可以使用存根。