2010-07-28 69 views
1

我最近刚刚将Devise添加到了我的第一个Rails3应用程序中,而且我在控制器测试中遇到了一些问题。用嘲讽测试两种不同的期望

我正在测试用户控制器类,它与Devise使用的是同一个模型。因此,在我的规范的开始,我有这样的:

before(:each) do 
    sign_in @user = Factory.create(:user) 
end 

现在我可以得到测试通过,而无需使用嘲讽或磕碰,像这样:

describe "GET edit" do 
    it "assigns the requested user as @user" do 
    user = Factory(:user) 
    get :edit, :id => user.id 
    assigns(:user).should eql(user) 
    end 
end 

但对于教育目的,我想知道如何为了让它与嘲笑和残片一起工作,通常它会是直截了当的,但似乎Devise在控制器操作之前调用User.find,并使测试失败。

describe "GET edit" do 
    it "assigns the requested user as @user" do 
    user = Factory(:user) 
    User.expects(:find).with(:first, :conditions => {:id => 37}).returns(user) 
    get :edit, :id => '37' 
    assigns(:user).should be(user) 
    end 
end 

还通过将twice到预期这也将失败,因为在第一次调用发现是一个我设定的预期不同。

任何有识之士将不胜感激。

回答

5

你可以像这样指定与任何stubsexpects多个返回值:

require 'test/unit' 
require 'mocha' 

class Foo 
end 

class FooTest < Test::Unit::TestCase 

    # This passes! 
    def test_multiple_returns_with_stubs 
    Foo.stubs(:find).returns('a').returns('b').returns('c') 

    assert_equal('a', Foo.find('z')) 
    assert_equal('b', Foo.find('y')) 
    assert_equal('c', Foo.find('x')) 
    end 

    # This passes too! 
    def test_multiple_returns_with_expects 
    Foo.expects(:find).times(1..3).returns('a').returns('b').returns('c') 

    assert_equal('a', Foo.find('z')) 
    assert_equal('b', Foo.find('y')) 
    assert_equal('c', Foo.find('x')) 
    end 
end 

的区别,显然,是expects需要知道它是怎么回事了多少次被调用。如果您未指定任何内容,则会假定为once,并且会在随后的调用中投诉。 stubs不在乎。

+0

非常感谢,我得出了类似的结论。对于不同的调用有不同的'.with'有什么解决办法吗?我想另一种解决方法是将Devise的地狱存根出来...... – stuartc 2010-07-30 08:37:13