Rspec控制器测试未通过验证,但具有有效数据

时间:2014-11-30 20:14:54

标签: ruby-on-rails validation rspec

我正在尝试使用工厂女孩的Rspec为我的更新路线编写一个控制器测试,但即使我非常确定工厂中的数据是有效的,我也无法通过验证。

这是我的工厂:

FactoryGirl.define do
  factory :user do
    username { Faker::Internet.user_name(8) }
    password 'password'
  end
  factory :post do
    title { Faker::Lorem.sentence }
    body { Faker::Lorem.paragraph }
    author { Faker::Internet.user_name(8) }
  end
end

这是我的模特:

class Post < ActiveRecord::Base
  validates :title, :body, :author, presence: true
end

这是我的测试:

require 'rails_helper'

describe PostsController  do
    let!(:user) { FactoryGirl.create :user }
    let!(:post) { FactoryGirl.create :post }
    let(:attributes) { FactoryGirl.attributes_for :post }

describe 'PUT #update' do
  let(:title) { "A treatise on Malomars." }
  it 'updates a field on a blog post' do
      put :update, id: post.id, post: {title: title}
      expect(post.reload.title).to eq(post.title)
    end
  end
end

我得到的错误是:

 Failure/Error: put :update, id: post.id, post: {title: title}
 ActiveRecord::RecordInvalid:
   Validation failed: Body can't be blank

EDIT --- 这是控制器:

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def new
  end

  def create
    post = Post.new
    post.title = params[:title]
    post.body = params[:body]
    post.author = "#{session[:username].titleize} Force"
    redirect_to root_path
    post.save!
  end

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

  def update
    post = Post.find(params[:id])
    post.title = params[:post][:title]
    post.body = params[:post][:body]
    post.save!
    redirect_to root_path
  end

  def destroy
    post = Post.find(params[:id])
    post.destroy
    redirect_to root_path
  end
end

1 个答案:

答案 0 :(得分:0)

除了强参数之外,您将post.body设置为nil,因为您没有在测试中传递body参数的值。当您在控制器中致电save!时,您会收到错误消息,因为您已确认存在body(即不是nil)。