在 rspec 2 中,我可以做到这一点。
let(:user_1) { create :user_1) # factoryGirl 对象
User.stub(:where).and_return(user_1)
user_1.stub(:where).and_return(user_1)
但在 rspec 3 中,它发生了故障。
let(:user_1) { create :user_1) # factoryGirl 对象
allow(User).to receive(:where).and_return(user_1)
allow(user_1).to receive(:where).and_return(user_1) # 这一行出现失败
错误信息是,
失败/错误:allow(product_1).to receive(:where).and_return(product_1)
#<User ..... object description.... >
不实施:哪里
我应该怎么做才能通过这个例子?
---------- 更新问题----------
在控制器中,
operators = Admin
if !params[:name].blank?
operators = operators.where('adm_name like ?', '%' + params[:name] + '%')
end
if !params[:login_id].blank?
operators = operators.where('adm_login_id like ?', '%' + params[:login_id] + '%')
end
if params[:status] != "all"
operators = operators.where('status=?', params[:status])
end
if !params[:id_check].blank?
operators = operators.where('adm_login_id = ?', params[:id_check])
end
在规范中,
let(:admin) { create :admin }
before do
allow(Admin).to receive(:where).and_return(admin)
allow(admin).to receive(:where).and_return(admin)
end
it 'should be success' do
get :search, params
expect(response).to be_success
end
那么失败消息是,
Failure/Error: allow(admin).to receive(:where).and_return(admin)
#<Admin ... object description ...> does not implement: where
before
首先,我在块中删除了这个语句,
allow(admin).to receive(:where).and_return(admin)
然后我收到一条失败消息,
NoMethodError:
undefined method `first' for #<Admin:0x007f99d2e166d0>
所以我尝试了这个(返回数组),
allow(Admin).to receive(:where).and_return([admin])
然后我收到一条失败消息,
NoMethodError:
undefined method `where' for #<Array:0x007f9a67313e28>