简体   繁体   English

Rspec / Capybara-应该把变化变成预期

[英]Rspec/Capybara - change should into expect

In my Ruby on Rails 4.2 app, I would like to change a test checking inline style to the rspec 3 more recent "expect" on a "should" but i get an error. 在我的Ruby on Rails 4.2应用程序中,我想将测试检查内联样式更改为rspec 3,并在“应该”上更新了“期望”,但出现错误。

When I use the test below, my test passes: 当我使用下面的测试时,我的测试通过了:

find('#zone')['style'].should == "background-image: url(xxxxx); background-size: cover;"

I tried to convert it to rspec more recent "expect" 我试图将其转换为rspec更新的“期望”

expect('#zone')['style'].to eq("background-image: url(xxxxx); background-size: cover;")

but I get this error: 但是我得到这个错误:

undefined method `[]' for #<RSpec::Expectations::ExpectationTarget:0x00000008578840>

How to achieve this? 如何实现呢?

expect(find('#zone')['style']).to eq "background-image...."

In general, something.should == is equivalent to writing expect(something).to eq 通常, something.should ==等同于将expect(something).to eq写入expect(something).to eq

There are some subtle differences ("bug fixes", if you like) on objects that use delegated methods, or implement methods such as should themselves; 使用委托方法的对象或实现should自身的方法的对象之间存在细微的差异(如果需要,可以“错误修复”)。 but for the most part I wouldn't worry about that; 但在大多数情况下,我不会为此担心。 you can consider the two formats equivalent, but should always aim to use the new expect format. 您可以考虑将两种格式等效,但是应始终以使用新的expect格式为目标。

One other nice conversion is that if you wrote tests that use the (sometimes implicitly defined) subject variable - eg subject.should ... , you can re-write this as either: expect(subject).to , or alternatively just: is_expected.to 另一种很好的转换是,如果您编写的测试使用(有时隐式定义的) subject变量(例如subject.should ... ,则可以将其重写为: is_expected.to expect(subject).to is_expected.to ,或者只是: is_expected.to

While the accepted answer is technically correct, it can potentially lead to flaky tests if you have a dynamic page. 尽管从技术上来说,可接受的答案是正确的,但是如果您有动态页面,则可能会导致测试不稳定。 This can happen when the element where the style attribute is being checked is being updated due to a JS action, and the check can occur before the style has changed. 当由于JS操作而正在更新要检查style属性的元素时,可能会发生这种情况,并且检查可能在样式更改之前进行。 It's much better to write the expectation as 将期望写成

expect(page).to have_css('#zone[style="background-image: url(xxxxx); background-size: cover;"]')

or 要么

expect(find('#zone')).to match_css('[style="background-image: url(xxxxx); background-size: cover;"]')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM