如何测试变量未定义或RSpec中引发异常

时间:2016-02-17 04:17:25

标签: ruby-on-rails ruby rspec error-handling

在我的模型中,我正在动态设置范围

  AccountType.all_valid_types.each do |type| # AccountType.all_valid_types returns an array from database
    scope type.downcase.pluralize.split(' ').join('_').to_sym, -> { where(account_type: type) }
  end

在我的规范测试中,我试图测试all_valid_types的模型范围是否存在,并且当创建,更新或删除类型时,范围应相应调整...

实施

#account_type.rb:
after_save :reset_profile_scopes
after_destroy :reset_profile_scopes

def reset_profile_scopes
  #unset file
  Object.send(:remove_const, "Profile")

  #reload file
  load "profile.rb"
end

RSpec测试:

describe "Dynamism" do
  it "should ensure that the profile.rb file (Profile class) gets reloaded after each create, update, and destroy" do
    Profile.connection #hack to simulate profile load already
    account_type = FactoryGirl.create(:account_type)
    expect(Profile.send(account_type.name.pluralize)).to be_an(ActiveRecord::Relation)
    name = Faker::Lorem.word
    account_type.update_attribute(:name, name)
    expect(Profile.send(name.pluralize)).to be_an(ActiveRecord::Relation)
    account_type.destroy
    expect(Profile.send(name.pluralize)).to raise_error
  end
end

所有工作都在expect(Profile.send(name.pluralize)).to raise_error行。

我知道我希望它会抛出错误,但是如何编写规范以便它传递错误而不会抛出错误? (希望这不会令人困惑)

换句话说,我可以使用什么RSpec语法expect an error/exception

感谢。

1 个答案:

答案 0 :(得分:2)

如果我不得不猜测:

expect(Profile.send(name.pluralize)).to raise_error

到:

expect { Profile.send(name.pluralize) }.to raise_error