我刚刚开始使用 rspec 2,并且我认为在我的一个方法存根中的某个地方遇到了麻烦。我正在尝试从我的 clients_controller.rb 测试“显示”操作,但它失败了,返回一个 Enumerable::Enumerator 而不是一个对象。“索引”操作工作正常。我的目标是确保当前登录的用户可以查看他或她的客户,但不能查看任何其他用户的客户。
before_filter :require_user
def index
@clients = current_user.clients
end
def show
@client = current_user.clients.find(params[:id])
end
和:
before :each do
stub_current_user
@my_client = mock_model(Client, :user_id => @current_user.id)
@not_my_client = mock_model(Client, :user_id => @current_user.id + 1)
@current_user.stub!(:clients) { @clients = [@my_client] }
@clients.stub!(:find){ @my_client }
end
describe "GET index" do
it "assigns the current user's clients as @clients" do
get :index
assigns(:clients).should eq([@my_client])
end
end
describe "GET show" do
it "assigns the requested client as @client if @client is the current user's client" do
get :show, :id => @my_client.id
assigns(:client).should eq(@my_client)
end
it "does not assign the requested client if @client is not the current user's client" do
get :show, :id => @not_my_client.id
assigns(:client).should == nil
end
end
stub_current_user 在 spec_helpers.rb 中:
def stub_current_user
@current_user = mock_model(User, :name => 'Bob Johnson', :email => 'bob@johnson.com',
:role => "account_holder", :incomplete_subscription? => false,
:plan => mock_model(Plan, :client_limit => 5),
:monthly_rate => 100)
if defined?(controller) # for controller specs
controller.stub!(:current_user).and_return(@current_user)
elsif defined?(template) # for view specs
template.stub!(:current_user).and_return(@current_user)
else
'wat'
end
end
'index' 动作的测试通过了,但 'show' 动作的两个测试都失败了,出现以下错误:
1) ClientsController GET show assigns the requested client as @client if @client is the current user's client
Failure/Error: assigns(:client).should eq(@my_client)
expected #<Client:0x81b67840 @name="Client_1007">
got #<Enumerable::Enumerator:0x1036471d0>
(compared using ==)
Diff:
@@ -1,2 +1,2 @@
-#<Client:0x81b67840 @name="Client_1007">
+#<Enumerable::Enumerator:0x1036471d0>
# ./spec/controllers/clients_controller_spec.rb:31
2) ClientsController GET show does not assigns the requested client if @client is not the current user's client
Failure/Error: assigns(:client).should == nil
expected: nil,
got: #<Enumerable::Enumerator:0x1035336b8> (using ==)
# ./spec/controllers/clients_controller_spec.rb:39
我不确定我在模拟、测试本身或其他地方是否出错了。