rspec测试强大的参数并建立模型

时间:2014-02-13 17:34:46

标签: ruby-on-rails rspec

我正在尝试编写模型测试,如下所示:

require 'spec_helper'

describe Five9List do
  before :each do
    @five9_list = Five9List.new(name: 'test_list', size: '100')
  end

  describe "#new" do
    it "takes two parameters and returns a Five9List object" do
      @five9_list.should be_an_instance_of Five9List
    end
  end

  describe "#name" do
    it "returns the correct name" do
      @five9_list.name.should eql "test_list"
    end
  end
  describe "#size" do
    it "returns the correct size" do
      @five9_list.size.should eql 100
    end
  end
end

目前,这成功并且运行正常。那是因为我的模型正在使用attr_accessible,如下所示:

class Five9List < ActiveRecord::Base

  attr_accessible :name, :size

end

如果我想摆脱attr_accessible并遵循使用strong_params的rails 4惯例,我将如何将其写入rspec测试仍然成功的位置?

在我的控制器中添加:

private
  def five9_list_params
    params.require(:five9_list).permit(:name, :size)
  end

删除attr_accessible不起作用。

修改

以下是我从rspec .收到的错误:

Failures:

  1) Five9List#name returns the correct name
     Failure/Error: @five9_list.name.should eql "test_list"

       expected: "test_list"
            got: nil

       (compared using eql?)
     # ./spec/models/five9_list_spec.rb:16:in `block (3 levels) in <top (required)>'

  2) Five9List#size returns the correct size
     Failure/Error: @five9_list.size.should eql 100

       expected: 100
            got: nil

       (compared using eql?)
     # ./spec/models/five9_list_spec.rb:22:in `block (3 levels) in <top (required)>'

Finished in 0.03303 seconds
4 examples, 2 failures, 1 pending

Failed examples:

rspec ./spec/models/five9_list_spec.rb:15 # Five9List#name returns the correct name
rspec ./spec/models/five9_list_spec.rb:21 # Five9List#size returns the correct size

Randomized with seed 20608

1 个答案:

答案 0 :(得分:2)

您的规格没有任何问题。我只能猜测你没有运行Rails 4,或者你已经安装了ProtectedAttributes gem。