2017-11-06 1 views
0

テストで使用するデータを作成するRspecのロジックを理解することができません。Rspec + FactoryGirl:let文の配置が変数の作成やテストの使用に影響するのはなぜですか?

私はいくつかのシナリオを持ち、最初のシナリオ以外はすべてエラーになります。エラーは、ページを印刷するときに、レコードが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 

スペック/機能/ 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)聞かせて配置してください!最初の 'それはブロック

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 

UPDATE前の文:

私は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

答えて

0

:ここで私を助けた私が見つけたいくつかの参照があります作成されたものはユーザーまたは記事に関連付けられません(しかし、新しいユーザーと新しい記事)。

変数を検査していて、それはゼロですか、ページに表示されているものだけで行くのですか?あなたがページ上にあるもので行くなら、それは特定の記事/ユーザに関連するコメントだけを表示することが可能でしょうか?

他の問題として、beforeブロックは、describe変数の内部で作成されたコメント変数の前に実行されるため、ページに移動してからコメントが表示されます。

関連する問題