我试图测试我的应用,以便当用户投票选择某种食物时,user.votes的数量和food.votes都会上升。到目前为止,我无法做到这一点,而且我不确定我是否错误地写了我的测试,或者建立了一个不能让测试通过的工厂。它在我在控制台中手动测试时起作用,所以我知道它确实起作用,但是测试不同意。
FactoryGirl.define do
factory :vote do |f|
f.user_id user
f.food_id food
end
end
def create
@vote = Vote.new(vote_params)
if @vote.save
flash[:notice] = "Thanks for voting!"
else
flash[:notice] = "Something went wrong"
end
end
before(:each) do
@user = create(:user)
sign_in(@user)
@food = create(:food)
end
describe "POST #create" do
context "with valid attributes" do
it "creates a new vote" do
vote_params = FactoryGirl.attributes_for(:vote)
expect { post :create, params: { vote: vote_params } }.to change(Vote, :count).by(1)
end
it "Updates @user vote count" do
vote_params = FactoryGirl.attributes_for(:vote)
expect { post :create, params: { vote: vote_params } }.to change(@user.votes, :count).by(1)
end
it "Updates @food vote count" do
vote_params = FactoryGirl.attributes_for(:vote)
expect { post :create, params: { vote: vote_params } }.to change(@food.votes, :count).by(1)
end
end
end
Failures:
1) VotesController POST #create with valid attributes Updates @user vote count
Failure/Error: expect { post :create, params: { vote: vote_params } }.to change(@user.votes, :count).by(1)
expected #count to have changed by 1, but was changed by 0
# ./spec/controllers/votes_controller_spec.rb:27:in `block (4 levels) in <top (required)>'
2) VotesController POST #create with valid attributes Updates @food vote count
Failure/Error: expect { post :create, params: { vote: vote_params } }.to change(@food.votes, :count).by(1)
expected #count to have changed by 1, but was changed by 0
# ./spec/controllers/votes_controller_spec.rb:32:in `block (4 levels) in <top (required)>'
Finished in 2.99 seconds (files took 4.66 seconds to load)
36 examples, 2 failures
Failed examples:
rspec ./spec/controllers/votes_controller_spec.rb:25 # VotesController POST #create with valid attributes Updates @user vote count
rspec ./spec/controllers/votes_controller_spec.rb:30 # VotesController POST #create with valid attributes Updates @food vote count
答案 0 :(得分:0)
好的,有足够的信心来猜测。我认为,问题是vote_params
来自工厂(可能带有user_id / food_id的硬编码值) - 但不是您正在测试的真实@user
和@food
反对。您需要将这些值放入vote_params
我可以建议以下内容:
context "with valid attributes" do
# Set vote-params from factory, then merge in the @user/@food ids
let(:vote_params) { FactoryGirl.attributes_for(:vote).merge(:user_id => @user.id, :vote_id => @vote.id) }
it "creates a new vote" do
expect { post :create, params: { vote: vote_params } }.to change(Vote, :count).by(1)
end
it "Updates @user vote count" do
expect { post :create, params: { vote: vote_params } }.to change(@user.votes, :count).by(1)
end
it "Updates @food vote count" do
expect { post :create, params: { vote: vote_params } }.to change(@food.votes, :count).by(1)
end
end