Rails 4 Rspec 2.14控制器测试 - CREATE / UPDATE控制器测试中的字符串与整数?

时间:2014-01-21 01:18:06

标签: ruby-on-rails rspec ruby-on-rails-4

下面是rspec中的CREATE和UPDATE控制器测试 - 我正在测试使用嵌套发票项属性创建/更新发票对象。我的问题是为什么UPDATE测试要求我将整数指定为“字符串”,而CREATE测试不是?如果我不这样做,我会得到一个预期/得到的错误。

控制器创建测试

describe "PUT/POST actions" do

    describe "POST create" do 

      before do

        @invoice_item_attrs = {"0"=>{"description"=>"something", "line_total"=>1.0, "unit_cost" => 1.0, "quantity" => 1.0, "item" => "item", "invoice_id" => 1, "_destroy"=>false}}

        @client = FactoryGirl.build(:client, user: @user)

        @valid_invoice_params = HashWithIndifferentAccess.new(paid: true, date_sent: "Wed, 18 Dec 2013 00:19:00 +0000", client_id: "#{@client.id}", user_id: "#{@user.id}", invoice_items_attributes: @invoice_item_attrs)

      end

      describe "with valid params" do

        it "creates a new Invoice" do

          expect {

            post :create, {:invoice => @valid_invoice_params, :user_id => @user.id}

          }.to change(Invoice, :count).by(1)

        end

控制器更新测试

描述“PUT更新”做

  before do

    @invoice = FactoryGirl.create(:invoice, user: @user)

    @client = FactoryGirl.build(:client, user: @user)

    @invoice_item_attrs = {"0"=>{"description"=>"something", "line_total"=>"1.0", "unit_cost" => "1.0", "quantity" => "1.0", "item" => "item", "invoice_id" => "1", "_destroy"=>false}}

    @valid_invoice_params = HashWithIndifferentAccess.new(paid: true, date_sent: "Wed, 18 Dec 2021 00:19:00 +0000", client_id: "#{@client.id}", user_id: "#{@user.id}", invoice_items_attributes: @invoice_item_attrs)

  end

  describe "with valid params" do

    it "updates the requested invoice" do

      # Assuming there are no other invoices in the database, this

      # specifies that the Invoice created on the previous line

      # receives the :update_attributes message with whatever params are

      # submitted in the request.

      Invoice.any_instance.should_receive(:update).with(@valid_invoice_params)

      put :update, {:id => @invoice.to_param, :invoice => @valid_invoice_params, user_id: @user.to_param}

    end

1 个答案:

答案 0 :(得分:0)

您需要在update案例中指定字符串,因为您正在使用RSpec设置期望Invoice实例将接收的内容(即通过with(...)并且字符串不同于显然。在这种情况下,你所拥有的控制器代码将整数转换为字符串。

您可以在create情况下使用,因为您没有在那里设置任何参数期望,只是将哈希传递给某些生产代码(即通过post ...),这将很乐意接受。< / p>