【发布时间】:2013-02-17 23:55:00
【问题描述】:
这是间歇性失败的测试:
context "as a regular_user" do
before :each do
@user = FactoryGirl.create(:user, :role => 'regular_user')
visit new_user_session_path unless current_path == new_user_session_path
fill_in "Email", :with => @user.email
fill_in "Password", :with => @user.password
click_button "Sign In"
end
it "removes thing from favorites while on thing index page" do
@things = FactoryGirl.create_list(:thing, 5)
@user.set_mark :favorite, @things.first
@user.reload.favorite_things
visit things_path unless current_path == things_path
expect{
first(:link, "Remove from favorites").click # Sometimes this fails
@user.reload.favorite_things
}.to change { @user.favorite_things.count }.by(-1)
page.should have_content("Sort by")
end
end
我正在使用 gem markable 来提供收藏功能。
当我使用rspec 运行规范时,成功/失败似乎没有任何模式(它不像一旦失败就总是失败,反之亦然)。当规范通过guard(spork 也被使用)运行时,可能会出现一种模式,如果我启动guard 并且测试通过,那么它总是会在guard 的实例运行时通过。 .. 同样适用于失败 - 如果我启动 guard 并且它失败了,那么该 guard 实例中的所有后续运行也将失败。
刚才我运行rspec spec/requests/users_spec.rb:148 来运行那个规范,但它失败了:
1) Users as a regular_user removes thing from favorites while on thing index page
Failure/Error: click_link "Remove from favorites" # Sometimes this fails
Capybara::ElementNotFound:
Unable to find link "Remove from favorites"
# ./spec/requests/users_spec.rb:155:in `block (4 levels) in <top (required)>'
# ./spec/requests/users_spec.rb:153:in `block (3 levels) in <top (required)>'
在那之后我再次运行rspec spec/requests/users_spec.rb:148,它成功了:
Finished in 0.83754 seconds
1 example, 0 failures
我尝试在index.html.erb 视图文件的<% @things.each do |thing| %> 部分中添加“asdfasdf”,并使用page.should have_content("asdfasdf") 进行检查,但有时会失败。我尝试在expect 块之前添加page.should have_selector('.favoritesblock', visible: true)(favoritesblock 存在于视图中的同一@things 块中),但有时会失败。但是,它总是会在 <% @things.each do |thing| %> 循环之外找到文本。
我在first(:link, "Remove from favorites").click # Sometimes this fails 行之前添加了save_and_open_page,并且能够生成规范失败的实例。该页面仅包含两件事(我的 FactoryGirl 调用应该创建 5)并且它们都没有“从收藏夹中删除”链接(取决于该事物是否被收藏,它显示“添加到收藏夹”或“删除来自收藏夹”)。
基于此,我尝试稍微修改规范的前两行,但没有帮助(有时仍然失败):
5.times { FactoryGirl.create(:thing) }
@user.set_mark :favorite, Thing.first
我注意到的是,当它成功时,它确实会首先显示“从收藏夹中删除”链接,但并不总是显示所有 5 件事。
所以,我需要知道为什么这个规范会间歇性失败,或者我还能做些什么来找出导致问题的原因。有什么想法吗?
【问题讨论】:
-
你能发布你的工厂吗?还有对模型的任何限制 - 有时可能无法创建事物?
-
是的!谢谢!问题是我有一个字段
active,我在工厂中将其设置为f.active { [true, false].sample }。所以,有时它会成为一个活跃的东西,有时它会成为一个不活跃的东西。每当测试使第一件事不活动时,规范就没有任何东西可以标记为最喜欢的。我的解决方法是将我的规范更改为@things = FactoryGirl.create_list(:thing, 5, :active => true),以便它只为这个规范创建活动的东西。 -
很高兴你得到了排序:) 我不得不使用 Fabricator 处理类似的问题。
标签: ruby-on-rails capybara factory-bot rspec-rails