我有一个显示欢迎信息或视频的视图,具体取决于是否定义了@video
。我正在尝试为视图编写一些测试,但我似乎无法弄清楚如何定义@video
的定义。
以下是观点:
<div class="container" id="contents">
<% unless defined? @video %>
<div class="hero-unit">
<h1>
Khan-O-Tron<br />
<small>Khan Academy has a lot of great videos. So many, in fact, that choosing just one is kind of annoying. Click the button below and let us choose one for you!</small>
</h1><br />
<a class="btn btn-large btn-success" href="/random">Get Started By Watching A Tutorial</a>
</div>
<% else %>
<div class="hero-unit">
<h1><%= @video.title %><br /> <small><%= @video.description %></small></h1>
<br />
<%= raw @video.get_embed_code %>
</div>
<% end %>
</div>
以下是我的测试:
require 'spec_helper'
describe "[Static Pages]" do
describe "GET /" do
before { visit root_path }
subject { page }
describe "#hero-unit" do
describe "with @video not defined" do
it "should have an H1 tag with the text 'Khan-O-Tron'." do
should have_selector ".hero-unit h1", text: "Khan-O-Tron"
end
it "should have an H1 small tag with a description of our product." do
should have_selector ".hero-unit h1 small", text: "Khan Academy has a lot of great videos. So many, in fact, that choosing just one is kind of annoying. Click the button below and let us choose one for you!"
end
it "should have a link to /random with the text 'Get Started By Watching A Tutorial'" do
should have_link "Get Started By Watching A Tutorial", href: "/random"
end
end
describe "with @video defined" do
before { @video = FactoryGirl.create(:video) }
it "should have an H1 tag with the video's title" do
should have_selector ".hero-unit h1", text: @video.title
end
it "should have an H1 small tag with the video's description" do
should have_selector ".hero-unit h1 small", text: @video.description
end
it "should have the video embedded in the page" do
should have_selector "iframe"
end
end
end
end
end
为什么我使用@video
定义的FactoryGirl
变量不会传递给视图?
答案 0 :(得分:0)
那是因为您在定义visit root_path
之前正在执行@video
。在get root_path
块中的@video = ....
行后面添加before
,它应该有效。
顺便说一句,正确的方法是使用rspec助手:
在第一个before
块上方添加此内容:
let(:video) { FactoryGirl.create(:video) }
然后在您设置实例变量的第二个before
块中,将行替换为:
assign(:video, video)
最后在您的示例中,将@video
替换为video
。
更多信息here。