水豚访问页面,总是零

时间:2013-07-02 02:28:52

标签: ruby-on-rails rspec capybara

在我的规范中,我正在访问一个页面并检查是否正确设置了一个实例变量。规范总是说assigns是零。查看保存的页面,它是空白的 - 不是404或任何类型的错误页面。

describe ArtistsController do
    before :each do
        @artist = Artist.first
    end
    describe "GET #about" do
        it "finds artist by artistname" do
            visit artist_about_path(@artist.artistname); save_page
            puts "2 ===================== #{ artist_about_path(@artist.artistname) }"
            # assigns(:artist).should eq(@artist)
            assigns[:artist].should_not be_nil
        end
        it "renders the :about view" do
            visit artist_about_path(@artist.artistname)
            # response.should render_template :about
            response.should be_success
        end
    end
# Similar specs for other pages to be rendered

Artist.first来自一个rake任务,该任务在spec_helper中运行以填充数据库;该部分在其他测试中正常工作。

我正在通过打印检查路径,看起来很好。控制器方法:

class ArtistsController < ApplicationController
before_filter :get_artist_from_params
def about
    @artist = Artist.find_by_artistname(params[:artistname].downcase)
    @contact_info = @artist.contact_info
    puts "1 ==============================="
    puts @artist.inspect
  end

在服务器日志中,@artist是我们期望的对象。

def get_artist_from_params
    if !params[:artistname].blank?
      @artist = Artist.find_by_artistname(params[:artistname].downcase)
      if @artist.blank?
        not_found
      end
    end
end

我不确定测试出错的地方...... puts正在输出正确的值。

使用Ruby 2.0,Rails 3.2,Capybara 2.1,Rspec 2.12。

1 个答案:

答案 0 :(得分:1)

我对此测试感到有点困惑,但也许我可以帮助支持一些。

我认为你可以将你的行动留空:

def about
end

然后你可以这样清理你的before_filter:

private

def get_artist_from_params
  if params[:artistname]
    @artist = Artist.find_by_artistname(params[:artistname].downcase)
    if @artist
      @contact_info = @artist.contact_info
    else
      not_found
    end
  end
end

首先,老实说,如果您只想确保在控制器中正确设置实例变量,我认为您不需要进行集成测试。我相信你想进行功能测试,如http://guides.rubyonrails.org/testing.html#what-to-include-in-your-functional-tests所示。好吧,让我们看看我们到目前为止是否可以做到这一点:

describe ArtistsController do
  let(:artist) { Artist.first } #May want to look into FactoryGirl
  describe "GET #about" do
    before :each do
      @parameters = { artistname: artist.name }
      Artist.should_receive(:find_by_artistname).with(artist.name.downcase).and_return(artist)
    end
    it "assigns artist and contact_info instance variables" do
      get :about, @parameters
      assigns(:artist).should eq(artist)
      assigns(:contact_info).should eq(artist.contact_info)
    end
    it "responds successfully" do
      get :about, @parameters
      expect(response).to be_success
    end
    it "renders about template" do
      get :about, @parameters
      expect(response).to render_template("about")
    end
  end
end

如果有意义我可以提供其他详细信息,请告诉我。