测试对象由current_user拥有或创建

时间:2012-03-30 10:03:33

标签: ruby-on-rails rspec

我目前正在尝试从教程中创建一个Dropbox-esque应用程序,但我无法弄清楚如何测试此控制器。

这是AssetsController页面

    def index
       @assets = current_user.assets
    end

    def show
       @assets = current_user.assets.find(params[:id])

此外,资产belongs_to:用户和用户has_many:assets

我如何将其纳入rspec测试?

2 个答案:

答案 0 :(得分:3)

首先,要非常小心AssetsController。

假设您使用的是Rails 3,“assets_path”也是用于加载应用程序资产的路径,因此,您在该控制器中写入会话的任何内容都将被静默忽略。可能不是你想要的!我强烈考虑重命名控制器。

我首先在登录栏中创建用户

module ControllerMacros
  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      @user = Factory.create(:user)
      sign_in @user
    end
  end
end

然后,您可以在spec_helper.rb文件

中加载它
RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
end

最后,你可以在测试中使用它

describe MyController do
  context "#index" do
    login_user
    before(:each) do
      @assets = []
      5.times{ @assets << Factory.create(:asset, :user => @user)}
    end

    it "should test index" do
      get :index
      assigns(:assets).should eq(@assets)
    end
  end
end

现在,这应该正确测试您的资产列表。

编辑:刚才意识到,我在这里使用FactoryGirl / Devise,你可能会也可能不会!

答案 1 :(得分:1)

你到底有什么问题?如何设置关系的基本测试或如何测试current_user的管理?

对此的基本测试应该在Model Specs中,因为模型的工作就是理清这些东西。

我通常会这样测试:

1)为两个用户和一些资产(本例中为三个)定义灯具(或者使用类似FactoryGirl的东西)。用户a的资产名为asset_a_ *,用户名为b asset_b _ *)

2)测试就像这样:

   users(:users_a).assets.should have(3).records
   users(:users_a).assets.should include(assets(:asset_a_a))
   users(:users_a).assets.should include(assets(:assets_a_b))
   users(:users_a).assets.should include(assets(:assets_a_c))

你可以像这样微调 users(:users_a).assets.find(assets(:asset_a_a).id)。应包含(assets(:asset_a_a)) users(:users_a).assets.find(assets(:asset_a_a).id).should_not include(assets(:asset_b_a))

如果您绝对需要,可以对控制器部件使用类似的测试。

虽然有很多讨论,如果这些基本功能需要测试,因为它主要是核心Rails功能来处理你在模型中定义的关联。

我个人会因某些原因进行此类测试。在许多情况下,此类许可相关协会很快变得更加复杂,无论如何都需要详细的测试或者有人可能会改变关联的参数并破坏某些东西。

II - 关于控制器中的current_user部分。

这当然取决于您如何处理身份验证。如果您使用AuthLogic(或其他)之类的插件,它可能有一些允许在rspec中模拟登录的方法。对于authlogic,您可以执行以下操作:

before(:each) do
  activate_authlogic
  UserSession.create(users(:user_a))
end

这将激活authlogic和'login'user_a。 然后你运行控制器

  get :index
  response.should be_success
  response.should render_template :index
  assigns(:assets).should # => more or less as above, check that there are the right aessets.