2013-05-28 36 views
0

我想为某个正在测试的特定实例设置“true”的存在。它目前不存在,所以它的存在== false。为RSpec测试设置存在为true

下面是我到目前为止的代码。希望有人能帮忙。

在invitations_controller

def join_request 
    invitation_options = {recipient_id: current_user.id, project_id: @project.id, recipient_email: current_user.email} 

    if ProjectInvitation.where(invitation_options).present? 
    flash[:notice] = "You already sent a request to join this project." 
    redirect_to :back 
    return 
    end 

在invitations_controller_spec:

describe "Send Join Request" do 
    before do 
    @invitation_options = {:recipient_id => @user.id, :project_id => @project.id, :recipient_email => '[email protected]'} 
    ProjectInvitation.where(@invitation_options).present? == true # This is what I'm stuck on. Pretty sure this doesn't work. 
    end 
    context "if you already sent a request" do 
    it "should tell you that you already sent a request" do 
     response.should have_text("You already sent a request to join this project.") 
    end 
    it "should redirect you to the previous page" do 
     response.should redirect_to(:back) 
    end 
    end 
end 

回答

0

你可以很容易地存根'where'方法,但是它会保存你对这个模型的所有查询。例如:

Profile.stub(:where) { "555" } 
Profile.where(:id => 5) #will return 555 
Profile.where(:name => 'Phil') #will return 555 

但是,最好的方法是使用FactoryGirl产生ProjectInvitation

0

考虑ProjectInvitation提取这个查询(ProjectInvitation.where(invitation_options).present?)一类的方法,然后在您的测试存根它

+0

感谢您的建议。但是,这是否意味着我仍然需要创建所有这些值?是否没有办法将这个条目的存在设置为“true”这个特定的实例? – blanckien

0

存根current_user方法。创建一个工厂项目然后 只需在您的规范中创建带有属性{recipient_id: current_user.id,project_id:@ project.id,recipient_email: current_user.email}的ProjectInvitation。

+1

谢谢。考虑使用FactoryGirl来做到这一点。 – blanckien