0

我有一个显示欢迎消息或视频的视图,具体取决于是否@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没有传递给视图?

4

1 回答 1

0

那是因为您在visit root_path定义@video. 在块中的行get root_path之后添加它应该可以工作。@video = ....before

顺便说一句,解决这个问题的正确方法是使用 rspec 助手:

before在第一个块的正上方添加:

let(:video) { FactoryGirl.create(:video) }

然后在before您设置实例变量的第二个块中,将该行替换为:

assign(:video, video)

最后在您的示例中,替换@videovideo.

更多信息在这里

于 2013-04-17T04:48:06.560 回答