使用rspec和capybara在POST和UPDATE控制器测试中获得nil

时间:2014-10-05 15:15:36

标签: ruby-on-rails rspec controller

只需运行一个脚手架,然后添加相应的测试。由于某种原因,UPDATE和POST方法无法正常工作,并以" nil"进行响应。无法找到原因。用户控制器具有基本的REST方法。 ApplicationController包含一个before_filter:

before_filter :authenticate_user

protected
def authenticate_user
  unless User.find_by_id(session[:user_id])
    redirect_to root_path, notice: "Please log in"
  end
end

user_controller_spec:

describe "POST create" do
describe "with valid params" do
  it "creates a new User" do
    expect {
      post :create, {:user => valid_attributes}, valid_session
    }.to change(User, :count).by(1)
  end

  it "assigns a newly created user as @user" do
    post :create, {:user => valid_attributes}
    expect(assigns(:user)).to be_a(User)
    expect(assigns(:user)).to be_persisted
  end

  it "redirects to the created user" do
    post :create, {:user => valid_attributes}
    expect(response).to redirect_to(User.last)
  end
end

describe "with invalid params" do
  it "assigns a newly created but unsaved user as @user" do
    allow_any_instance_of(User).to receive(:save).and_return(false)
    post :create, {:user => { "email" => "invalid value" }}
    expect(assigns(:user)).to be_a_new(User)
  end

  it "re-renders the 'new' template" do
    allow_any_instance_of(User).to receive(:save).and_return(false)
    post :create, {:user => { "email" => "invalid value" }}
    expect(response).to render_template("new")
  end
end
end

describe "PUT update" do
describe "with valid params" do
  it "updates the requested user" do
    user = FactoryGirl.create(:user)
    expect_any_instance_of(User).to receive(:update).with({ "email" => "user@email.com" })
    put :update, {:id => team.to_param, :user => { "email" => "user@email.com" }}
  end

  it "assigns the requested user as @user" do
    user = FactoryGirl.create(:user)
    put :update, {:id => user.to_param, :user => valid_attributes}
    expect(assigns(:user)).to eq(user)
  end

  it "redirects to the user" do
    user = FactoryGirl.create(:user)
    put :update, {:id => user.to_param, :user => valid_attributes}
    expect(response).to redirect_to(user)
  end
end

describe "with invalid params" do
  it "assigns the user as @user" do
    user = FactoryGirl.create(:user)
    allow_any_instance_of(User).to receive(:save).and_return(false)
    put :update, {:id => user.to_param, :user => { "email" => "invalid value" }}
    expect(assigns(:user)).to eq(user)
  end

  it "re-renders the 'edit' template" do
    user = FactoryGirl.create(:user)
    allow_any_instance_of(User).to receive(:save).and_return(false)
    put :update, {:id => user.to_param, :user => { "name" => "invalid value" }}
    expect(response).to render_template("edit")
  end
end
end

1 个答案:

答案 0 :(得分:0)

尝试添加render_views。因为RSpec试图加速规范,默认情况下它不会渲染视图。