如何存根users_controller | authlogic,rspec2,rails3,factory_girl

时间:2010-09-07 15:35:34

标签: ruby-on-rails ruby-on-rails-3 rspec authlogic factory-bot

我的users_controller.rb

# GET /users/1/edit
def edit
  @user = current_user
  #@user = User.find(params[:id])
end

我看起来很甜蜜的users_controller_spec.rb(注意我所有已注释掉的尝试)

describe "Authenticated examples" do
  before(:each) do
    activate_authlogic
    UserSession.create Factory.build(:valid_user)
  end

describe "GET edit" do
  it "assigns the requested user as @user" do
    @user = Factory.create(:valid_user)
    assigns(:user).should be(Factory.build(:valid_user))
  end
end

user.rb - 工厂

Factory.define :valid_user, :class => User do |u|
  u.username "Trippy"
  u.password "password"
  u.password_confirmation "password"
  u.email "elephant@gmail.com"
  u.single_access_token "k3cFzLIQnZ4MHRmJvJzg"
end

基本上我只是想让这个RSpec测试以最恰当的方式传递。

我需要能够非常简单地说,mock_usercurrent_user

如果我在users_controller.rb中使用@user = User.find(params[:id])

,则会通过此测试

谢谢!

3 个答案:

答案 0 :(得分:4)

rspec-rails中存在一个错误(参见https://github.com/rspec/rspec-rails/issues/391),在挂钩之前在RSpec的全局中使用时会破坏activate_authlogic。

而不是

# spec_helper.rb

# In RSpec.configure
config.before :each, :type => :controller do
  activate_authlogic
  user = User.new(:login => "user", :password => "secret")
  UserSession.create(user)
end

你可以定义一个助手

# spec_helper.rb

require 'authlogic/test_case'
module LoginHelper
  include Authlogic::TestCase

  def login_user
    activate_authlogic
    user = User.new(:login => "user", :password => "secret")
    UserSession.create(user)
  end
end

并在需要时在前一个块中引用它

# <controller>_spec.rb

describe "GET 'edit' when logged in" do
  before do
    login_user
  end

  it "should be successful" do
    get 'edit'
    response.should be_success
end

答案 1 :(得分:3)

我不确定这是否适用于Rspec 2,但根据Authlogic文档,您需要将其放在before方法或spec_helper中:

include Authlogic::TestCase
activate_authlogic

然后您可以像在测试环境之外那样创建用户会话。

FWIW我放弃了Authlogic示例中的模拟/存根,然后执行@user = Factory.create(:user),然后使用UserSession.create(@user)登录。

修改

这是尝试使用您提供的示例。我认为您遇到的问题是assigns中的对象与您匹配的对象不同。

describe "Authenticated examples" do
  before(:each) do
    # assuming you put include Authlogic::TestCase in spec_helper
    activate_authlogic
    @user = Factory.create(:valid_user)
    UserSession.create(@user)
  end

describe "GET edit" do
  it "assigns the requested user as @user" do
   # add a MyModel.stub!(:find) here if the edit action needs it
   get :id => 1 # pass in an ID so the controller doesn't complain
   assigns(:user).should == @user
  end
end

答案 2 :(得分:1)

所有内容都在此页面上:

http://rdoc.info/github/binarylogic/authlogic/master/Authlogic/TestCase

您需要提供一些信息:

 require "authlogic/test_case" # include at the top of test_helper.rb
  setup :activate_authlogic # run before tests are executed
  UserSession.create(users(:whomever)) # logs a user in

在这种情况下,您只需要通过users(:whomever)

更改mock_user