【发布时间】:2017-11-06 08:18:33
【问题描述】:
我很难理解创建数据以在测试中使用的 Rspec 逻辑。
我有几种情况,除了第一种情况外,所有情况都会导致错误。错误意味着当我打印页面时,记录没有在 HTML 中呈现,这意味着没有创建变量。
这是我的工厂:
文章:
FactoryGirl.define do
factory :article do
title "First test article"
summary "Summary of first article"
description "This is the first test article."
user
end
end
评论:
FactoryGirl.define do
factory :comment do
sequence(:content) { |n| "comment text #{n}" }
article
user
end
end
spec/features/article_spec.rb
1) 在 rspec 测试中显式创建注释变量。
require 'rails_helper'
describe "Comments on article" do
let!(:user) { FactoryGirl.create(:user) }
let!(:article) { FactoryGirl.create(:article) }
let!(:comment) {Comment.create(content:"Some comments", article_id: article.id, user_id: user.id)}
before do
login_as(user, :scope => :user)
visit article_path(article)
end
describe 'edit', js: true do
let!(:comment) {Comment.create(content:"Some comments", article_id: article.id, user_id: user.id)}
it 'a comment can be edited through ajax' do
print page.html
find("a[href = '/articles/#{article.friendly_id}/comments/#{comment.id}/edit']").click
expect(page).to have_css('#comment-content', text: "Some comments")
within('.card-block') do
fill_in 'comment[content]', with: "Edited comments"
click_on "Save"
end
expect(page).to have_css('#comment-content', text: "Edited comments")
end
end
结束
2) 替换 let!(:comment) {Comment.create(content:"Some comments", article_id: article.id, user_id: user.id)} 如下:
let!(:comment) { FactoryGirl.create(:comment) }
3) 放置让!第一个“it”块之前的语句
describe 'edit', js: true do
let!(:comment) {Comment.create(content:"Some comments", article_id: article.id, user_id: user.id)}
it 'a comment can be edited through ajax' do
print page.html
find("a[href = '/articles/#{article.friendly_id}/comments/#{comment.id}/edit']").click
expect(page).to have_css('#comment-content', text: "Some comments")
within('.card-block') do
fill_in 'comment[content]', with: "Edited comments"
click_on "Save"
end
expect(page).to have_css('#comment-content', text: "Edited comments")
end
end
更新:
我发现设置测试数据/变量对我作为 Rspec 新手来说是一个很大的痛苦/绊脚石。以下是我发现的一些对我有帮助的参考资料:
1) When is using instance variables more advantageous than using let()?
2) https://www.ombulabs.com/blog/rails/rspec/ruby/let-vs-instance.html
【问题讨论】:
标签: ruby-on-rails rspec factory-bot