我正在尝试编写功能测试。我的测试如下所示:
describe PostsController do
it "should create a Post" do
Post.should_receive(:new).once
post :create, { :post => { :caption => "ThePost", :category => "MyCategory" } }
end
end
我的 PostsController(实际上是它的一部分)如下所示:
PostController < ActiveRecord::Base
def create
@post = Post.new(params[:post])
end
end
运行测试时,我总是遇到失败,这表明 Post 类期望 :new 但从未得到它。尽管如此,实际的帖子还是被创建了。
我是 RSpec 的新手。我错过了什么吗?
最佳答案
编辑 - 扔掉之前的垃圾
这应该做你想做的
require File.dirname(__FILE__) + '/../spec_helper'
describe PostsController do
it "should create a Post" do
attributes = {"Category" => "MyCategory", "caption" => "ThePost"}
Post.stub!(:new).and_return(@post = mock_model(Post, :save => false))
Post.should_receive(:new).with( attributes ).and_return @post
post :create, { :post => attributes }
end
end
这假设您正在使用 rspecs 自己的模拟库,并且您已经安装了 rspec_rails gem。
关于ruby-on-rails - RSpec:测试 Controller 时对模型的期望不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2738569/