【问题标题】:RSpec expectation ignoring message argumentRSpec期望忽略消息参数
【发布时间】:2016-06-27 09:04:25
【问题描述】:

有人理解为什么下面的期望忽略了参数消息,因为它是作为字符串传递的?

spec.rb

context 'flash' do
  context 'fail' do
    # Changes the admin_user so it has no permission to delete offence
    it 'flash[:alert]' do
      admin_user = FactoryGirl.create :admin_user
      sign_in admin_user
      delete :destroy,  :id => offence.id, :customer_id => offence.job.customer.id
      expect(flash[:alert]).to(be_present, eq("Deletion failed. Incident can only be deleted by user who created it!"))
    end
  end
end

控制器

 def destroy
  @offence = Offence.find(params[:id])
  @events = Event.where(sub_type: 'offence').where("parent_data->> 'id' = ?", @offence.id.to_s)
  if @offence.admin_user == current_user
  ActiveRecord::Base.transaction do
    @events.each do |event|
      event.destroy!
    end
    @offence.destroy!
    redirect_to admin_customer_offences_path(@customer), notice: 'Incident deleted successfully'
  end
  else
    redirect_to admin_customer_offences_path(@customer), alert: 'Deletion failed. Incident can only be deleted by user who created it!'
  end
 end

警告信息

.WARNING: ignoring the provided expectation message argument (#<RSpec::Matchers::BuiltIn::Eq:0x007fac42c5d4b0 @expected="Incident deleted successfully">) since it is not a string or a proc.

【问题讨论】:

  • 如果分成2个期望是一样的吗:be_present和.eq?
  • 是的。这很好用。只是想知道这是否不是有效的语法以及为什么。不过,现在使用该选项。谢谢

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


【解决方案1】:

这不是有效的 Rspec 用法。您假设 to 能够处理 2 个或更多期望。

你应该把它们分开

  expect(flash[:alert]).to be_present
  expect(flash[:alert]).to eq("Deletion failed. Incident can only be deleted by user who created it!")

但是,您的代码也是多余的。如果消息等于一个字符串,它肯定存在。因此,第一个期望完全没有用。

只需添加

  expect(flash[:alert]).to eq("Deletion failed. Incident can only be deleted by user who created it!")

【讨论】:

  • 我同意你的看法@Simone Carletii。我昨天意识到那是多余的。按照你的建议,我只保留了第二行。
  • '您假设 to 能够处理 2 个或更多期望。'这个复合期望不是和你上面说的背道而驰吗? relishapp.com/rspec/rspec-expectations/v/3-4/docs/…。我同意,如果有一个字符串作为 flash,它就会出现。但在另一种情况下,您可能需要将 2 个期望传递给 #to,那么上面的语法似乎可以工作。
  • 复合期望的语法肯定与您的示例不同。
【解决方案2】:

第二个参数用于自定义失败消息:

https://www.relishapp.com/rspec/rspec-expectations/v/3-4/docs/customized-message

但在这里,您似乎正在尝试将两种期望结合起来。为此,您需要使用复合语法:

https://www.relishapp.com/rspec/rspec-expectations/v/3-4/docs/compound-expectations

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多