2016-04-25 40 views
-1

我用的水豚测试此代码位于我的评价模型后隐藏(5分钟是常规):Link不一段时间豚

def editable? 
    self.created_at < (Time.now - 5.minute) 
end 

链接的观点:

- unless comment.editable? 
    = link_to 'Edit', edit_category_theme_comment_path(@category, @theme, comment) 

所以5分钟后链接编辑必须从页面隐藏(但我们需要刷新页面)。这是我在RSpec的代码创建的意见和测试链路隐藏功能:

def create_comment(options={}) 
    options[:content] ||= 'I am a comment' 

    visit category_theme_path(category, theme) 
    within '.comment-form' do 
    fill_in 'Content', with: options[:content] 
    click_button 'Submit' 
    end 
end 

context 'Comment has content' do 
    before(:each) { create_comment } 

    it 'hides the edit symbol due 5 minutes after comment was created' do 
    using_wait_time 400 do 
     visit category_theme_path(category, theme) 
     save_and_open_page 
     expect(page).to have_no_css('.comment-edit') 
    end 
    end 

end 

但我得到:Failure/Error: expect(page).to have_no_css('.comment-edit')expected #has_no_css?(".comment-edit") to return true, got false

我也尝试使用page.reload!expect(page).to have_no_css('.comment-edit', wait: 400)和其他相关人员,但水豚不要”我不想等。也许我用using_wait_time来说明一个错误的地方,如果那样的话 - 我该如何测试?

enter image description here

+0

有你的测试等待5分钟,声音不能接受我。任何其他方式可以测试这种行为? –

+0

仍处于亏损状态...... – k1r8r0wn

+0

你可以显示你的'create_comment'方法吗? –

回答

1

有许多事情错了你的方式来测试这一点。你尝试失败的原因是因为using_wait_time只是设置Capybaras匹配器等待他们期望成为真实的时间量,它实际上并没有使程序等待。因此,expect(page).to have_no_css('.comment-edit')将等待您的using_wait_time指定的时间,对内容每50毫秒左右重新检查页面,但它不会重新加载页面,也不会在加载页面之前等待。然而,为了您的工作方式,你需要访问的页面

it 'hides the edit symbol due 5 minutes after comment was created' do 
    sleep 5.minutes  
    visit category_theme_path(category, theme) 
    save_and_open_page 
    expect(page).to have_no_css('.comment-edit') 
end 

之前睡觉,这是一个可怕的想法,因为你的测试会变得可笑缓慢。

而不是那种方法,你可以生成你的测试评论已经“老”(如pascal betz建议),使用像FactoryGirl和指定created_at是超过5分钟前​​。

FactoryGirl.create(:comment, created_at: 5.minutes.ago) 

,或者如果你想继续通过接口创建您的评论则包括类似的Timecop宝石,你可以做

Timecop.travel(5.minutes.from_now) do 
    visit category_theme_path(category, theme) 
    save_and_open_page 
    expect(page).to have_no_css('.comment-edit') 
end 

将访问页面前5分钟前进的时钟,然后一旦完成块就将其重置为正常。

此外,您editable?方法是在错误的方向比较,应该是

def editable? 
    self.created_at > (Time.now - 5.minute) 
end 

那么该视图应该

- if comment.editable? 
    = link_to 'Edit', edit_category_theme_comment_path(@category, @theme, comment) 
+0

非常感谢您的时间提供了很好的解释!我通过添加'Comment.last.update(created_at:5.minutes.ago)'来处理它,然后看到你的答案。也会尝试使用'Timecop'宝石来测试它。 – k1r8r0wn

1

与5分钟老访问该网页的种子数据的工作。像这样,你不需要等五分钟。

而且你的代码

- unless comment.editable? 
    = link_to 'Edit', edit_category_theme_comment_path(@category, @theme, comment) 

也许应该读

- if comment.editable? 
    = link_to 'Edit', edit_category_theme_comment_path(@category, @theme, comment) 
+0

感谢您的建议,关于使用if也是一个很好的评论。 – k1r8r0wn