2012-06-02 39 views
1

我需要一些帮助家伙,试图让这个测试通过,但没有运气。RSpec功能测试重定向到错误的地方

describe 'PUT posts/:id' do 

    describe 'with valid attributes' do 

    let(:mock_post) { mock_model('Post', title: 'hey! iam a mock!', description: 'a sexy model', location: 'everywhere') } 

    login_user 

    it 'should update the object and redirect to the post' do 
     Post.stub!(:find).with(mock_post.id).and_return(mock_post) 

     Post.any_instance.should_receive(:update_attributes).with({"these" => "params"}).and_return(true) 

     response.should redirect_to post_path(mock_post) 

     put :update, id: mock_post.id, post: { these: 'params' } 
    end 

    it 'should have a current_user' do 
     subject.current_user.should_not be_nil 
    end 

    end 

现在,我有一些像上面的测试,并得到以下错误:

1) PostsController PUT posts/:id with valid attributes should update the object and redirect to the post 
    Failure/Error: response.should redirect_to post_path(mock_post) 
     Expected response to be a <:redirect>, but was <200> 
    # ./spec/controllers/posts_controller_spec.rb:200:in `block (4 levels) in <top (required)>' 

PostsController:

class PostsController < ApplicationController 
    load_and_authorize_resource except: [:index, :show] 
    before_filter :authenticate_user!, except: [:index, :show, :tags] 
    before_filter :find_post, only: [:show, :edit, :update, :suspend, :suspend_alert] 

def update 
    if @post.update_attributes(params[:post]) 
    flash[:success] = 'Cool.' 
    redirect_to post_path(@post) 
    else 
    render :edit 
    end 
end 

protected 
    def find_post 
    @post = Post.find(params[:id]) 
    end 
end 

另外,我应该怎么写了render :edit测试部分?

+0

'login_user'应该在'前(:每个)'块; 请勿硬编码mock_post ID的值。只需调用它,即用'mock_post.id'替换'1001'; 使“放入”测试行为符合预期。重复每个示例的“put”测试操作。 – zetetic

+0

好的。按照您的指示更新了帖子。 'login_user'是我从'Devise' [wiki页面]复制的'ControllerMacro'(https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with -Rails -3-(和RSpec的))。 –

+0

检查'log/test.log',它可能会告诉你为什么重定向没有发生。 – zetetic

回答

2

您的规格永远不会调用控制器操作。尝试添加:

Post.any_instance. 
    should_receive(:update_attributes). 
    with({"these" => "params"}) 
put :update, :id => "1", :post => {"these" => "params"} 

要测试从调用update_attributes导致两个路径,在期望替代的价值:

it "should redirect when successful" do 
    Post.any_instance. 
    should_receive(:update_attributes). 
    with({"these" => "params"}). 
    and_return(true)` 
    response.should_redirect_to(post_path(@mock_post)) 
    put :update, :id => "1", :post => {"these" => "params"} 
end 

it "should render the edit page when unsuccessful" do 
    Post.any_instance. 
    should_receive(:update_attributes). 
    with({"these" => "params"}). 
    and_return(false)` 
    response.should render_template("edit") 
    put :update, :id => "1", :post => {"these" => "params"} 
end 
+0

嗨,谢谢,你从哪里得到@post?我没有一个。 –

+0

对不起。看我的编辑。 – zetetic

+0

我已更新我的帖子。我对代码做了一些更改,所以它几乎可以工作。请看一下。谢谢。 –