控制器规范.reload错误:没有将nil隐式转换为Hash

时间:2014-07-09 21:25:10

标签: ruby-on-rails rspec

当我尝试使用.reload来测试Update方法时,我的rspec测试失败了。

错误

Admin::CompaniesController PUT update valid attributes changes @company's attributes
 Failure/Error: @company.reload
 TypeError:
   no implicit conversion of nil into Hash
 # ./spec/controllers/admin/admin_companies_controller_spec.rb:81:in `block (4 levels) in <top (required)>'

规范

# spec/controllers/admin_companies_controller_spec.rb
describe 'PUT update' do
  before :each do
    @company = create(:company, name: "Rockstars", phone: "3035551212")
  end

  context "valid attributes" do
    it "changes @company's attributes" do
      put :update, id: @company, company: attributes_for(:company, name: "Fishstars")
      @company.reload       #line 81
      expect( @company.name ).to eq("Fishstars")
    end
  end
end

我有也试过(1)使用let!(),(同样的错误)

describe 'PUT update' do

  let!(:company)  { create(:company, name: "Rockstars", phone: "303555121d") }

  context "valid attributes" do
    it "changes company's attributes" do
      put :update, id: company, company: attributes_for(:company, name: "Fishstars")
      company.reload       #line 81
      expect( company.name ).to eq("Fishstars")
    end
  end
end

也试过(2)(同样的错误)

  before :each do
    @company = create(:company, name: "Rockstars", phone: "3035551212")
  end

  it "changes @company's attributes" do
    @attr = { name: "Fishstars" }
    put :update, id: @company.id, :company => @attr
    @company.reload
    expect( @company.name ).to eq("Fishstars")
  end

我的第一个想法是变量@company为nil,但如果我注释掉第81行(显示),则测试会按预期失败。

更新

在第81行之前插入'byebug'可以让我看到@company的样子:

(byebug) @company
#<Company id: 1, name: "Rockstars", hq_address: "MyString", hq_city: "MyString", hq_state: "MyString", country: "MyString", description: "Description 1", phone: "3035551212", email: "Example2email@gmail.com", owner_id: 2, contact_name: "MyString", created_at: "2014-07-11 19:02:24", updated_at: "2014-07-11 19:02:24", active: true, logo_file_name: nil, logo_content_type: nil, logo_file_size: nil, logo_updated_at: nil, slug: "rockstars", refund_policy: "Refund policy">

(byebug) @company.reload
TypeError Exception: no implicit conversion of nil into Hash
nil

1 个答案:

答案 0 :(得分:0)

我无法弄清楚为什么.reload无法正常工作,但是我用find_by_id调用替换了它,我的测试现在正常运行:

# new code - effectively tests the update method
@company = Company.find_by_id(@company)

# original code - causes errors
@company.reload       #line 81