2012-06-02 1 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. Просто назовите его, т. Е. Замените '1001' на' mock_post.id'; Сделать тест-тест «put» после ожидания. Повторите действие 'put' для каждого примера. – zetetic

+0

Хорошо. Обновите сообщение, следуя инструкциям. 'login_user' является' ControllerMacro', который я скопировал с страницы 'Devise' [wiki] (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

Я обновил свой пост. Я внесла некоторые изменения в код, поэтому он почти работает. Взгляни, пожалуйста. Спасибо. –

Смежные вопросы