【问题标题】:Rspec controller test not passing validations, but has valid dataRspec 控制器测试未通过验证,但具有有效数据
【发布时间】:2014-11-30 20:14:53
【问题描述】:

我正在尝试使用带有工厂女孩的 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

编辑--- 这是控制器:

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

【问题讨论】:

  • 控制器在哪里?
  • 控制器在 app/controllers 中

标签: ruby-on-rails validation rspec


【解决方案1】:

除了强参数,您将post.body 设置为nil,因为您没有在测试中传递body 参数的值。当您在控制器中调用 save! 时,您会收到错误消息,因为您验证了 body 是否存在(即不存在 nil)。

【讨论】:

  • 已将其更改为 put :update, id: post.id, post: {title: title, body: post.body} 它正在传递,现在。我想我认为身体已经存在,因为它已经存在于工厂中,但现在看它,我发现它必须以同样的方式传递。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多