将有效属性传递给控制器​​但未通过验证

时间:2014-09-06 16:51:56

标签: ruby-on-rails rspec

型号:

module V1
  class Player < ActiveRecord::Base

    validates :name, presence: true
    validates :default_pull_rate, numericality: true, allow_nil: false

    has_many :player_links

  end

end

Spec(我甚至尝试过显式设置内联的default_pull_rate):

 it "creates a new player" do

   expect { post :create, format: :json, player: FactoryGirl.attributes_for(:player, default_pull_rate: 5) }.to change(V1::Player, :count).by(1)
 end

厂:

FactoryGirl.define do
  factory :player, class: V1::Player do
    name "Frank"
    default_pull_rate 100
  end

控制器:

....
def create
  @player = Player.new(player_params)

  if @player.save!
    redirect_to @player
  end
end

private

def player_params
  params.require(:player).permit(:name, :default_pull_rated)
end

错误讯息:

ActiveRecord::RecordInvalid: Validation failed: Default pull rate is not a number

传递型号规格:

it "is invalid without a default_pull_rate" do
   expect(FactoryGirl.build(:player, default_pull_rate: nil)).to_not be_valid
 end

 it "is invalid when default_pull_rate is a string" do
   expect(FactoryGirl.build(:player, default_pull_rate: "fast")).to_not be_valid
 end

1 个答案:

答案 0 :(得分:1)

player_params中的错字?

def player_params
  params.require(:player).permit(:name, :default_pull_rated)
end

应为_rate而不是_rated

def player_params
  params.require(:player).permit(:name, :default_pull_rate)
end