Tôi đang cố gắng tạo phương thức trên một trình trợ giúp được xác định trong bộ điều khiển của tôi. Ví dụ:Không thể tạo phương thức trợ giúp với rspec
class ApplicationController < ActionController::Base
def current_user
@current_user ||= authenticated_user_method
end
helper_method :current_user
end
module SomeHelper
def do_something
current_user.call_a_method
end
end
Trong RSpec tôi:
describe SomeHelper
it "why cant i stub a helper method?!" do
helper.stub!(:current_user).and_return(@user)
helper.respond_to?(:current_user).should be_true # Fails
helper.do_something # Fails 'no method current_user'
end
end
Trong spec/support/authentication.rb
module RspecAuthentication
def sign_in(user)
controller.stub!(:current_user).and_return(user)
controller.stub!(:authenticate!).and_return(true)
helper.stub(:current_user).and_return(user) if respond_to?(:helper)
end
end
RSpec.configure do |config|
config.include RspecAuthentication, :type => :controller
config.include RspecAuthentication, :type => :view
config.include RspecAuthentication, :type => :helper
end
Tôi hỏi một câu hỏi tương tự here, nhưng giải quyết trên một công trình xung quanh. Hành vi kỳ lạ này đã leo lên một lần nữa và tôi muốn hiểu lý do tại sao công việc này không hoạt động.
CẬP NHẬT: Tôi nhận thấy rằng gọi controller.stub!(:current_user).and_return(@user)
trước helper.stub!(...)
là nguyên nhân gây ra hành vi này. Điều này là dễ dàng, đủ để sửa chữa trong spec/support/authentication.rb
, nhưng đây có phải là một lỗi trong Rspec? Tôi không thấy lý do tại sao nó sẽ được dự kiến sẽ không có thể stub một phương pháp trên một helper nếu nó đã được stubbed trên một bộ điều khiển.
Hãy thử stubbing phương pháp thông qua ApplicationController, vì đó là nơi nó được định nghĩa. 'ApplicationController.stub (: current_user => @user)' EDIT: Bây giờ tôi nghĩ rằng có thể không hoạt động. – dwhalen
Không, nó không hoạt động. Tôi đã thử 'any_instance' cũng không có may mắn. Tôi đã thực sự có nó làm việc, nhưng tôi là một chút bối rối (có thể đã tìm thấy một lỗi với rspec). Tôi sẽ sớm cập nhật câu hỏi. – Brad
Âm thanh như một lỗi. Nó chắc chắn là giá trị nộp một vấn đề tại https://github.com/rspec/rspec-mocks/issues (và cố gắng với phiên bản mới nhất). –