2015-03-08 69 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