Rspec测试,调用控制器方法收到NoMethodError

时间:2011-03-04 23:14:40

标签: ruby-on-rails rspec

所以我只是试图从RSpec中的用户控制器调用log_in方法

it "should get the index page" do
  @user = User.new({ :email => "employee@test.com" })
  log_in(@user)
  get 'index'
  response.should be_success
end

我得到的结果就像

1) EmployeesController GET 'index' should get the index page
   Failure/Error: log_in(user)
   NoMethodError:
     undefined method `log_in' for #<RSpec::Core::ExampleGroup::Nested_1:0x4ac0328>
   # ./spec/controllers/employees_controller_spec.rb:11:in `user_log_in'
   # ./spec/controllers/employees_controller_spec.rb:16:in `block (2 levels) in <top (required)>'

有人可以帮帮我吗?感谢

2011年3月11日编辑

这是UserController中的log_in方法

  def log_in(user)
    session[:current_user] = user.id
  end

2 个答案:

答案 0 :(得分:14)

如果要在RSpec控制器测试中调用控制器上的方法,可以使用以下命令。

subject.send(:log_in,@user)

它应该调用该方法。我不知道这是不是最好的做法。更好的方法是将已记录的login_in方法存根,如BurmajaM所示。

答案 1 :(得分:5)

为什么不存根logging_in?或者你的方法是什么。登录不是此规范的目标,所以存根!这是一个简单的例子,我如何规范具有before_filter的控制器动作:

class MyController < ApplicationController
  before_filter :logged_in?

  def index
  end
end



describe MyController do
  describe "GET 'index'" do
    context "when not logged in"
      # you want to be sure that before_filter is executed
      it "requires authentication" do
        controller.expects :logged_in?
        get 'index'
      end
      # you don't want to spec that it will redirect you to login_path
      # because that spec belongs to #logged_in? method specs
    end
    context "when authenticated" do
      before(:each) { controller.stubs :logged_in? }
      it "renders :index template" do
        get 'index'
        should render_template(:index)
      end
      it "spec other things your action does when user is logged in"
    end
  end
end
相关问题