奇怪的丢失在嵌套资源的RSpec控制器测试中需要密钥

时间:2015-03-13 16:40:16

标签: ruby-on-rails rspec

在RSpec中测试嵌套资源的Rails控制器(用于API)(订单has_many order_actions):

it "returns status OK" do
  order_action = create(:order_action)
  order_action.update_attribute(:order_id, @order.id)
  put :update, {:id => order_action.id, :order_id => @order.id, :order_action => valid_attributes}.merge(valid_session)
  expect(response.code).to eql("200")
end

valid_attributes只是build(:order_action).attributesvalid_session{:user_email => @user.email, :user_token => @user.authentication_token, :format => 'json'}。)

我收到一个恼人的错误missing required keys: [:order_id]。令人讨厌,因为正如你所看到的,它是上面明确定义的。两次。这是错误文本:

ActionController::UrlGenerationError:
  No route matches {:action=>"show", :controller=>"api/v1/order_actions", :format=>nil, :id=>#<OrderAction id: 19, order_id: 3, created_at: "2015-03-13 15:52:13", updated_at: "2015-03-13 15:52:13">, :order_id=>nil} missing required keys: [:order_id]

相关的失败测试报告

rspec ./spec/controllers/order_actions_controller_spec.rb:151 # Api::V1::OrderActionsController PUT #update with valid params returns status OK

请注意两个错误::order_id:formatnil

现在,如果你单独进行完全相同的测试,事情会更加怪异:

$ rspec spec/controllers/order_actions_controller_spec.rb:151
Run options: include {:locations=>{"./spec/controllers/order_actions_controller_spec.rb"=>[151]}}
.

Finished in 0.16575 seconds (files took 3.62 seconds to load)
1 example, 0 failures

测试通过!我失去了理智。帮助


其他信息

@order顶部创建

@userorder_actions_controller_spec.rb

before(:each) do
  @user = create(:user)
  @order = create(:order)
end

订单和用户工厂:

a_user = User.new({:email => "#{SecureRandom.hex(3)}@rakuten.com", :password => "!abc123%@#", :password_confirmation =>  "!abc123%@#"})

FactoryGirl.define do
  factory :order do
    user a_user
    class_code "MyText"
    class_name "MyString"
    complete false
  end
end

FactoryGirl.define do
  factory :user do
    email "#{SecureRandom.hex(3)}@email.com"
    password "!abc123%@#"
    password_confirmation { "!abc123%@#" }
  end
end

0 个答案:

没有答案