好的,所以我的主要问题是我已经在我们的项目中实现了 Mailboxer 来处理消息传递,并且我正在尝试为它编写测试。然而,我一次又一次地跌跌撞撞。我尝试了几种不同的存根/模拟,但没有取得任何进展。
我们有一个依赖于 before_filters 的 conversations_controller.rb 来设置执行每个操作所需的所有实例变量。然后在控制器动作中,直接引用实例变量来执行任何类型的动作或返回特定数据。
下面是我们的索引操作的示例,它返回在 before_filter 中指定的“框”中的所有对话,邮箱也在另一个 before_filter 中指定:
class ConversationsController < ::ApplicationController
before_filter :get_user_mailbox, only: [:index, :new_message, :show_message, :mark_as_read, :mark_as_unread, :create_message, :reply_message, :update, :destroy_message, :untrash]
before_filter :get_box
def index
if @box.eql? "inbox"
@conversations = @mailbox.inbox
elsif @box.eql? "sentbox"
@conversations = @mailbox.sentbox
else
@conversations = @mailbox.trash
end
end
在过滤器之前:
private
def get_user_mailbox
@user = User.where(:user_name => user.user_name.downcase).where(:email => user.email.downcase).first_or_create
@mailbox = @user.mailbox if @user
end
def get_box
if params[:box].blank? or !["inbox","sentbox","trash"].include?params[:box]
params[:box] = 'inbox'
end
@box = params[:box]
end
所以我想我有两个问题合二为一。首先,如何让我的测试生成索引操作所需的正确数据@mailbox、@user 和@box。接下来,我如何传递 fake 参数以将 @box 设置为不同的“inbox/sentbox/trash”。我已经尝试过 controller.index({box: "inbox"}) 但总是收到“错误的参数 1 for 0”消息。
我以各种不同的方式尝试了以下方法,但总是得到 nil:class 错误,这意味着我的实例变量肯定没有正确设置。
describe "GET 'index' returns correct mailbox box" do
before :each do
@user = User.where(:user_name => 'test').where(:email => 'test@test.com').first_or_create
@mailbox = @user.mailbox
end
it "#index returns inbox when box = 'inbox'" do
mock_model User
User.stub_chain(:where, :where).and_return(@user)
controller.index.should == @mailbox.inbox
end
end