2015-03-08 107 views
0

我對測試仍然相當陌生,至今仍圍繞着Factory Girl,我認爲這是造成這種故障的罪魁禍首。就像解決方案可能會很簡單一樣,我已經用相同的失敗信息搜索了其他帖子,但答案對我來說並不合適。工廠女孩和Rspec控制器測試失敗

我決定通過構建這個簡單的博客應用程序來學習BDD/TDD。下面是失敗消息:

Failures: 

    1) PostsController POST create creates a post 
    Failure/Error: expect(response).to redirect_to(post_path(post)) 
     Expected response to be a <redirect>, but was <200> 

測試:

RSpec.describe PostsController, :type => :controller do 
    let(:post) { build_stubbed(:post) } 

    describe "POST create" do 
     it "creates a post" do 
      expect(response).to redirect_to(post_path(post)) 
      expect(assigns(:post).title).to eq('Kicking back') 
      expect(flash[:notice]).to eq("Your post has been saved!") 
     end 
    end 
end 

我的工廠女孩​​文件:

FactoryGirl.define do 
    factory :post do 
     title 'First title ever' 
     body 'Forage paleo aesthetic food truck. Bespoke gastropub pork belly, tattooed readymade chambray keffiyeh Truffaut ennui trust fund you probably haven\'t heard of them tousled.' 
    end 
end 

控制器:

class PostsController < ApplicationController 

    def index 
     @posts = Post.all.order('created_at DESC') 
    end 

    def new 
     @post = Post.new 
    end 

    def create 
     @post = Post.new(post_params) 

     if @post.save 
      flash[:notice] = "Your post has been saved!" 
     else 
      flash[:notice] = "There was an error saving your post." 
     end 
     redirect_to @post 
    end 

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

    private 

    def post_params 
     params.require(:post).permit(:title, :body) 
    end 
end 

如果它是相關的,這是我的Gemfile:

gem 'rails', '4.1.6' 

... 

group :development, :test do 
    gem 'rspec-rails', '~> 3.1.0' 
    gem 'factory_girl_rails', '~> 4.5.0' 
    gem 'shoulda-matchers', require: false 
    gem 'capybara' 
end 

任何幫助表示讚賞。

回答

1

試試這個爲你的測試:

context 'with valid attributes' do 
    it 'creates the post' do 
    post :create, post: attributes_for(:post) 
    expect(Post.count).to eq(1) 
    end 

    it 'redirects to the "show" action for the new post' do 
    post :create, post: attributes_for(:post) 
    expect(response).to redirect_to Post.first 
    end 
end 

個人我還分離出一些你沒有在不同的測試者預計。但是,我不知道在控制器中測試它們是如何設置的。

編輯: 您的創建操作也存在一個問題,如果它未成功保存,將仍嘗試重定向到將失敗的@post。您使用無效屬性的測試應該強調這一點。

+0

感謝您的迴應!我絕對同意這些期望看起來更好。我嘗試了它們,但第一個規範通過但第二個規範仍然失敗: '失敗/錯誤:post:create,event:attributes_for(:post) ActionController :: ParameterMissing: param丟失或值爲空: ' – shroy 2015-03-08 22:34:34

+0

糟糕 - 更新了我的答案...複製並粘貼受害人:^) – patrick 2015-03-08 22:45:44

+0

很高興再次看到綠色!感謝Patrick! – shroy 2015-03-08 22:50:50