繁体   English   中英

Factory Girl和Rspec控制器测试失败

[英]Factory Girl & Rspec controller test failure

我对测试还是相当陌生,并且仍然将我的头缠在Factory Girl上,我认为这是这次失败的罪魁祸首。 该解决方案可能会很简单,但我搜索了其他帖子,但带有相同的失败消息,但答案对我不起作用。

我决定通过构建此简单的博客应用程序来学习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

任何帮助表示赞赏。

尝试以下方法进行测试:

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,这将失败。 具有无效属性的测试应突出显示这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM